File Handling in PHP

File handling in PHP helps you manage files and directories effectively. You can open, read, write, append, close, delete, and even rename files using built-in PHP functions. These operations are useful when dealing with data storage, configuration, log files, or uploads. This guide covers essential file handling operations with practical examples and explanations.


Opening Files

To start file operations, use the fopen() function to open or create a file.

Syntax:

fopen(filename, mode);
  • filename – Name of the file to open

  • mode – Type of operation (read, write, append, etc.)

Example:

$handle = fopen("data.txt", "r");

This opens the file in read-only mode.

Common Modes:

  • r – Read-only; file must exist

  • r+ – Read and write; file must exist

  • w – Write-only; creates a new file or clears existing

  • w+ – Read and write; creates or truncates

  • a – Append-only

  • a+ – Read and append

  • x – Create new file; fails if exists

  • x+ – Create and read/write; fails if exists


Checking File Existence

Before accessing a file, it’s a good idea to check if it exists to avoid errors.

Example:

if (file_exists("data.txt")) {
    // File is safe to use
}

Other checks:

  • is_file() – Verifies if path is a file

  • is_readable() – Confirms readability

  • is_writable() – Confirms writability


Closing Files

Once file operations are complete, close the file to free up system resources.

Example:

fclose($handle);

Reading Files

PHP supports several functions to read data from files.

a) fread() – Reads a specific number of bytes

$content = fread($handle, filesize("data.txt"));

b) file_get_contents() – Reads full content as string

$content = file_get_contents("data.txt");

c) readfile() – Outputs file contents directly

readfile("data.txt");

d) file() – Reads file into an array

$lines = file("data.txt");
foreach ($lines as $line) {
    echo $line;
}

e) fgets() – Reads one line at a time

while (!feof($handle)) {
    echo fgets($handle);
}

f) fgetc() – Reads one character at a time

while (!feof($handle)) {
    echo fgetc($handle);
}

Writing Files

To save data into a file, you can use different writing methods.

a) fwrite() – Writes string to a file

$handle = fopen("note.txt", "w");
fwrite($handle, "Hello World");
fclose($handle);

b) file_put_contents() – Simplified writing

file_put_contents("note.txt", "Hello World");

To append instead of overwrite:

file_put_contents("note.txt", "New line", FILE_APPEND);

Appending Data

Appending lets you add content to the end of an existing file.

file_put_contents("note.txt", "Appended line", FILE_APPEND);

Error Handling

Handle file errors to avoid script crashes.

Example:

if (!$handle = fopen("data.txt", "r")) {
    die("File could not be opened.");
}

You may also use custom error handlers:

set_error_handler("customHandler");

Renaming Files

To rename or move files:

rename("old.txt", "new.txt");

Deleting Files

To delete a file from the system:

unlink("note.txt");

Creating Directories

Use the mkdir() function to create folders.

mkdir("uploads");

You can also set permissions or create nested folders using optional parameters.


Deleting Directories

To remove a directory (must be empty):

rmdir("uploads");

Listing Directory Contents

a) scandir() – Lists files and directories

$items = scandir("mydir");

b) Recursive listing

function listAllFiles($dir) {
    $files = scandir($dir);
    foreach ($files as $file) {
        if ($file != "." && $file != "..") {
            echo $file . "<br>";
        }
    }
}

c) glob() – Lists matching files

foreach (glob("docs/*.txt") as $file) {
    echo basename($file);
}

Copying Files

You can duplicate a file using:

copy("a.txt", "b.txt");

Temporary Files

To use a temporary file:

$temp = tmpfile();
fwrite($temp, "Temporary Data");

File Locking

To avoid conflicts in multi-user environments, lock files during write operations.

$handle = fopen("file.txt", "a");
if (flock($handle, LOCK_EX)) {
    fwrite($handle, "Locked data");
    flock($handle, LOCK_UN);
}
fclose($handle);

File Metadata

File size:

filesize("data.txt");

File type:

filetype("data.txt");

Absolute path:

realpath("data.txt");

Clear stat cache:

clearstatcache();

Summary

PHP provides a wide set of functions to handle both text and binary files. Whether you’re reading line-by-line, writing logs, appending records, or managing directories, these tools allow for safe and flexible file management. With error handling, locking, and metadata access, you can build robust file operations for your application.

Â