PHP File Handling

PHP can read from and write to files on the server, making it possible to store data, generate reports, and process uploaded content without a database.

What is file handling?

File handling means using PHP to interact with files stored on the server's disk: opening them, reading their contents, adding new data, or creating them from scratch. It is useful for tasks like keeping a log of events, saving user-generated text, exporting data to a downloadable file, or reading a configuration stored as plain text.

PHP offers two styles of file access. The simple functions, such as file_get_contents() and file_put_contents(), handle a whole file in a single call and are perfect for small files. The lower-level functions, fopen(), fread(), fwrite(), and fclose(), give you a file handle so you can work through a file step by step, which matters for large files or when you need fine control.

Reading and writing a whole file at once

<?php
// Write a string to a file (creates it if missing)
file_put_contents("notes.txt", "First line of text\n");

// Read the entire file back into a string
$content = file_get_contents("notes.txt");
echo $content;
?>

Checking files before you use them

Before opening or reading a file it is wise to confirm it actually exists and is readable, otherwise PHP will emit warnings. A handful of small functions answer these questions and help your script fail gracefully.

FunctionPurpose
file_exists()Returns true if the file or directory exists
is_readable()Returns true if the file can be read
is_writable()Returns true if the file can be written to
filesize()Returns the file size in bytes
unlink()Deletes a file

Guarding against a missing file

<?php
$path = "notes.txt";

if (file_exists($path) && is_readable($path)) {
    echo file_get_contents($path);
} else {
    echo "The file could not be read.";
}
?>
Note: Never build a file path directly from user input. A visitor could supply something like '../../etc/passwd' to reach sensitive files. Always validate the name and restrict access to a known directory.

The workflow of low-level file access

  • Open the file with fopen(), passing a filename and a mode such as 'r' or 'w'.
  • Read from it with fread() or fgets(), or write to it with fwrite().
  • Always close the file with fclose() when you are done to free the resource.
  • For very large files, read line by line in a loop instead of loading everything into memory.

Exercise: PHP File Handling

What happens when fopen() is called in "w" mode on a file that already exists?