PHP File Handling

PHP File Handling

PHP has a rich set of functions for reading, writing, and managing files on the server.

1 - Read Entire File

// As string
$content = file_get_contents("data.txt");

// As array of lines
$lines = file("data.txt", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
foreach ($lines as $line) {
    echo $line . "<br>";
}

2 - Write and Append

// Overwrite (or create)
file_put_contents("log.txt", "First entry\n");

// Append
file_put_contents("log.txt", "Second entry\n", FILE_APPEND | LOCK_EX);

3 - fopen / fclose Pattern (Large Files)

$handle = fopen("big-data.txt", "r");
if ($handle) {
    while (!feof($handle)) {
        $line = fgets($handle, 4096);
        // process $line
    }
    fclose($handle);
}

4 - File Info and Management

file_exists("data.txt");    // true/false
filesize("data.txt");       // size in bytes
filemtime("data.txt");      // last modified timestamp
is_readable("data.txt");
is_writable("data.txt");
copy("src.txt", "dst.txt"); // copy file
rename("old.txt", "new.txt"); // move/rename
unlink("delete-me.txt");    // delete file
mkdir("uploads", 0755, true); // create directory

Note: For large files, always use fopen()/fgets() instead of file_get_contents(). Loading a 500 MB file into a string will exhaust PHP's memory limit instantly.

-Tip-