Interacting with the Server's File System
Beyond just processing user input, a powerful feature of any server-side language is its ability to interact with the server's file system. PHP provides simple and effective functions to read from and write to files, allowing you to create logs, store configuration data, cache information, and much more.
1. Reading an Entire File
The easiest way to read the full content of a file into a single string is by using the file_get_contents()
function. This is perfect for reading smaller configuration files or templates.
Example:
First, create a new file in your htdocs/php-course
folder named welcome.txt
and put the following text inside it: Hello from a text file!
Now, create a PHP file to read it:
<?php
$filename = "welcome.txt";
// Check if the file exists before trying to read it
if (file_exists($filename)) {
$content = file_get_contents($filename);
echo "<pre>" . $content . "</pre>";
} else {
echo "The file " . $filename . " does not exist.";
}
?>
Note: While convenient, file_get_contents()
loads the entire file into memory. It might not be suitable for reading very large files (e.g., several gigabytes).
2. Writing to a File (Overwrite)
The simplest way to write data to a file is with the file_put_contents()
function. It takes two main arguments: the filename and the data you want to write.
Important: By default, this function will create the file if it doesn't exist. If the file already exists, it will be completely overwritten with the new data.
<?php
$filename = "data.txt";
$content_to_write = "This is the first line of our new file.";
file_put_contents($filename, $content_to_write);
echo "File written successfully. Check your folder for data.txt!";
?>
3. Appending to a File
What if you want to add new content to a file without erasing what's already there? You can do this by providing a third argument to file_put_contents()
: the FILE_APPEND
flag.
This is extremely useful for things like log files, where you add a new entry each time an event happens.
<?php
$log_file = "activity.log";
// The "\n" is a special character that represents a new line
$log_entry = "New event occurred at: " . date("Y-m-d H:i:s") . "\n";
// The FILE_APPEND flag tells the function to add to the end of the file
file_put_contents($log_file, $log_entry, FILE_APPEND);
echo "New entry added to the log file.";
?>
File handling is a powerful tool, but always be cautious about security. Never allow user input to dictate file paths directly, as this can lead to serious vulnerabilities. We'll learn more about handling user-submitted files safely in the next lesson about file uploads.