File Handling refers to the ability to read from and write data to files stored on your server’s filesystem. This is essential for tasks like creating error logs, managing simple configuration settings, or processing user-uploaded text files (like CSVs).
1. The File Lifecycle
Working with files in PHP follows a strict three-step lifecycle:
- Open: Use the
fopen()function to open the file and prepare it for reading or writing. - Operate: Use functions like
fread()orfwrite()to perform the action. - Close: Use the
fclose()function to close the file handle, releasing system resources.
2. Opening Files (fopen()) and Modes
The fopen() function takes two arguments: the path to the file and the mode (what you intend to do with the file).
| Mode | Purpose | Pointer Position | Action if File Does Not Exist |
r | Read Only | Start of the file. | Fails |
w | Write Only | Start of the file. Overwrites existing content! | Creates a new file |
a | Append Only | End of the file. Adds to existing content. | Creates a new file |
r+ | Read and Write | Start of the file. | Fails |
w+ | Read and Write | Start of the file. Overwrites existing content! | Creates a new file |
Example:
<?php
$filename = "server_log.txt";
// Attempt to open the file for appending (a)
$handle = fopen($filename, "a") or die("Unable to open file!");
?>
3. Reading a File (fread() and fgets())
Once a file is opened for reading (r or r+ mode), you can retrieve its contents.
Reading the Entire File (fread())
The fread() function reads the entire contents of a file until the end is reached. It requires the file handle and the size of the file (which you can get using the filesize() function).
Example:
<?php
$filename = "config.txt";
$handle = fopen($filename, "r") or die("Error opening file!");
// Read the entire file content at once
$content = fread($handle, filesize($filename));
fclose($handle);
echo $content;
?>
Reading Line by Line (fgets())
The fgets() function reads only a single line from the file at a time. This is useful when you need to process a large file efficiently without loading the entire thing into memory.
<?php
$handle = fopen("log.txt", "r");
// Loop until the end-of-file (feof()) marker is reached
while (!feof($handle)) {
echo fgets($handle) . "<br>";
}
fclose($handle);
?>
4. Writing to a File (fwrite())
The fwrite() function is used to write content to a file. It takes the file handle and the string data you want to write.
Example: Writing and Appending a Log Entry
<?php
$log_file = "activity.log";
$log_entry = date("Y-m-d H:i:s") . " - User logged out.\n";
// 1. Open in Append mode ('a') to add to the end of the file
$handle = fopen($log_file, "a");
// 2. Write the log entry
fwrite($handle, $log_entry);
// 3. Close the file
fclose($handle);
echo "Log updated successfully.";
?>
Note: If you used the
wmode instead ofa, every time you run the script, the file would be completely wiped and replaced with the new log entry.
5. File Permissions and Safety
File handling often involves permissions. If PHP cannot read or write to a file, it will fail. On Linux/macOS servers, you may need to adjust the file’s permissions (CHMOD) to allow the web server user to write to it.
| Function | Purpose |
file_exists() | Checks if a file or directory exists. |
unlink() | Deletes a specified file. |
Example:
<?php
$file = "old_temp.txt";
if (file_exists($file)) {
if (unlink($file)) {
echo $file . " was successfully deleted.";
} else {
echo "Error deleting file.";
}
}
?>
Next Steps
File handling completes the core set of practical tasks. The next major step is to introduce Object-Oriented Programming (OOP), which is essential for writing modern, maintainable PHP code.
