PHP File Handling: Open, Read, Write, and Append Files


File handling is a fundamental aspect of web development, allowing PHP to interact with files on the server. Whether you need to read configuration files, write logs, or store user data, PHP provides powerful functions for file operations.



1. Opening a File in PHP

Before performing any file operation, you must open the file using fopen().

Syntax:

$file_handle = fopen("filename.txt", "mode");

File Modes:

Mode Description
r Read-only (file pointer at the beginning)
r+ Read/write (file pointer at the beginning)
w Write-only (creates a new file or truncates existing)
w+ Read/write (creates or truncates)
a Append-only (file pointer at the end)
a+ Read/append (file pointer at the end)
x Write-only (creates new file, fails if exists)
x+ Read/write (creates new file, fails if exists)

Example: Opening a File

$file = fopen("example.txt", "r") or die("Unable to open file!");
  • If the file doesn't exist, fopen() returns false.
  • Always check if the file opened successfully.


2. Reading a File in PHP

PHP provides multiple ways to read file content:

a. fread() – Read Fixed Bytes

$file = fopen("example.txt", "r");
$content = fread($file, filesize("example.txt"));
fclose($file);
echo $content;
  • Reads up to filesize() bytes.
  • Useful for binary files.

b. fgets() – Read Line by Line

$file = fopen("example.txt", "r");
while(!feof($file)) {
    echo fgets($file) . "<br>";
}
fclose($file);
  • Reads one line at a time.
  • Best for log files and CSV parsing.

c. file() – Read into Array

$lines = file("example.txt");
foreach ($lines as $line) {
    echo $line . "<br>";
}
  • Each line becomes an array element.
  • Useful for config files.

d. file_get_contents() – Read Entire File

$content = file_get_contents("example.txt");
echo $content;
  • Simplest method for small files.
  • No need to manually open/close.


3. Writing to a File in PHP

a. fwrite() – Write to File

$file = fopen("example.txt", "w");
fwrite($file, "Hello, PHP File Handling!");
fclose($file);
  • Overwrites existing content (mode w).
  • Use a mode to append instead of overwrite.

b. file_put_contents() – Quick Write

file_put_contents("example.txt", "New content");
  • Shortcut for fopen() + fwrite() + fclose().
  • Overwrites by default (use FILE_APPEND flag to append).


4. Appending to a File

To add content without deleting existing data, use a mode or FILE_APPEND.

a. Using fopen() + fwrite()

$file = fopen("example.txt", "a");
fwrite($file, "\nAppended line.");
fclose($file);

b. Using file_put_contents() with FILE_APPEND

file_put_contents("example.txt", "\nAnother line.", FILE_APPEND);
  • Appends text without overwriting.


5. Closing a File

Always close files after operations to free resources:

$file = fopen("example.txt", "r");
// ... file operations ...
fclose($file);
  • Not needed for file() or file_get_contents().


6. Checking File Existence

Before working with files, check if they exist:

if (file_exists("example.txt")) {
    echo "File exists!";
} else {
    echo "File not found!";
}
  • Also useful: is_readable(), is_writable().


7. Error Handling in File Operations

Always handle errors gracefully:

$file = @fopen("nonexistent.txt", "r");
if (!$file) {
    die("Error: Could not open file!");
}
  • Use @ to suppress default PHP warnings.

Log errors in production:

error_log("File error: " . error_get_last()['message']);


Complete Example: Read, Write, and Append

// Write to a new file
file_put_contents("data.txt", "Line 1\n");

// Append more data
file_put_contents("data.txt", "Line 2\n", FILE_APPEND);

// Read and display
echo file_get_contents("data.txt");

Output:

Line 1
Line 2


Best Practices for PHP File Handling

  • Check file permissions (is_readable(), is_writable()).
  • Use absolute paths (/var/www/data.txt instead of data.txt).
  • Lock files when writing (flock() prevents race conditions).
  • Sanitize filenames to prevent directory traversal:
    $filename = basename($_POST['filename']); // Removes ../ attacks
  • Avoid storing sensitive data in plain text.
  • Close files after operations (fclose()).