Beyond databases, web applications frequently interact directly with server filesystems—such as writing transaction audit logs, reading configuration files, parsing CSV spreadsheets, and caching HTML pages. PHP provides robust, C-level File Handling functions that allow you to create, read, write, append, and lock files on the server safely.
fopen)When you open a file handle with fopen($filename, $mode), the mode dictates read/write permissions and cursor positioning:
| Mode | Operations Allowed | File Pointer Position & Behavior |
|---|---|---|
"r" |
Read Only | Starts at file beginning. Returns false if file does not exist. |
"w" |
Write Only | Truncates file to 0 length (erases old content!). Creates file if missing. |
"a" |
Append Only | Starts at file end (preserves existing content). Creates file if missing. |
"r+" |
Read & Write | Starts at file beginning without truncating. |
"w+" |
Read & Write | Truncates file to 0 length. Creates file if missing. |
"a+" |
Read & Append | Reads anywhere, writes strictly at file end. Preserves data. |
fwrite)<?php
$logFile = "student_access.log";
// Open file in append mode ('a')
$handle = fopen($logFile, "a");
if ($handle) {
$timestamp = date("Y-m-d H:i:s");
$logEntry = "[$timestamp] User Vikram logged in from IP 192.168.1.10\n";
// Write log entry to file
fwrite($handle, $logEntry);
// Always close open file streams!
fclose($handle);
echo "Log entry appended successfully.";
} else {
echo "Error: Unable to open file for writing.";
}
?>
fgets and feof)For large files that exceed PHP's memory limit, reading line-by-line with fgets() is the professional practice:
<?php
$handle = fopen("student_access.log", "r");
if ($handle) {
echo "<h4>Access Audit Trail:</h4><pre>";
// feof() checks if end-of-file has been reached
while (!feof($handle)) {
$line = fgets($handle); // Reads one line at a time
echo htmlspecialchars($line);
}
echo "</pre>";
fclose($handle);
}
?>
file_get_contents() & file_put_contents()When you simply want to read or write an entire file in one clean line of code:
<?php
// Read entire file into string
$content = file_get_contents("notes.txt");
// Write string to file (FILE_APPEND flag appends rather than overwriting)
file_put_contents("notes.txt", "New lecture notes added.\n", FILE_APPEND | LOCK_EX);
?>
High-Frequency Exam Question:
Q: What is file locking in PHP and why is flock() important?
A: In a concurrent web environment, multiple visitors might attempt to write to the same file simultaneously, resulting in file corruption (race condition). flock($handle, LOCK_EX) applies an exclusive lock during writes, forcing other processes to wait until the write completes.
Exercise 28.1: Create a text-based website hit counter using file_get_contents() and file_put_contents().
Exercise 28.2: Write a script that checks whether a file exists using file_exists() and displays its size in Kilobytes using filesize().