Modern PHP offers high-level functions that treat files as simple streams of data. These functions are often preferred over the basic fopen/fclose structure for common tasks because they open, read/write, and close the file automatically in a single call.
1. Reading an Entire File into a String
The easiest way to read a file is to pull its entire contents into a single string variable.
| Function | Purpose | Layman’s Term |
file_get_contents() | Reads the entire file into a string. The recommended way to read small/medium files. | Suck the whole file in. |
readfile() | Reads the file and writes the content directly to the output buffer (the browser). Returns the number of bytes read. | Print the file directly. |
Example: Reading a Configuration File
<?php
$config_path = 'app_settings.json';
if (file_exists($config_path)) {
// Read the entire JSON file into the $json_string variable
$json_string = file_get_contents($config_path);
// Convert the JSON string into a PHP array for use
$settings = json_decode($json_string, true);
echo "Site Title: " . $settings['site_title'];
}
?>
2. Reading a File into an Array
If your file contains list data where each line is a separate item (like a log file or a list of users), you can read it directly into an array.
| Function | Purpose |
file() | Reads the entire file and places each line into a separate element of an array. |
Example: Processing a Log File
<?php
$log_file = 'access_log.txt';
// Reads file; each element in $log_entries contains one line, including the newline character
$log_entries = file($log_file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
echo "Total log entries: " . count($log_entries) . "<br>";
echo "First entry: " . $log_entries[0];
?>
Note: The optional flags
FILE_IGNORE_NEW_LINESandFILE_SKIP_EMPTY_LINESare excellent for cleaning up the resulting array immediately.
3. Writing Data to a File
The counterpart to file_get_contents() is the simple function for writing data.
| Function | Purpose | Layman’s Term |
file_put_contents() | Writes data to a file. It handles opening, writing, and closing the file automatically. | Dump this data into the file. |
Example: Updating a Status File
<?php
$status_file = 'server_status.txt';
$new_status = "Status: OK. Last updated: " . date("H:i:s");
// Default behavior is to OVERWRITE the file
$bytes_written = file_put_contents($status_file, $new_status);
if ($bytes_written !== false) {
echo "Successfully wrote $bytes_written bytes.";
}
?>
Appending Data (Adding to the End)
To add content to the end of an existing file (like appending to a log), you use a special flag:
<?php
$log_entry = "\n[WARNING] Critical resource approaching limit.";
// Use the FILE_APPEND flag to add data to the end of the file
file_put_contents($status_file, $log_entry, FILE_APPEND);
echo "New warning appended to the status file.";
?>
4. Advanced File Information
For checking file status and permissions, these simple functions are often used:
| Function | Purpose |
filesize() | Returns the size of the file in bytes. |
is_writable() | Checks if PHP can write to the specified file or directory. |
touch() | Creates an empty file if it doesn’t exist, or updates the modification time if it does. |
unlink() | Deletes a specified file from the filesystem. |
