PHP File Handling

PHP file handling lets your scripts read and write files on the server, from simple logs to CSV reports and user uploads. PHP offers quick one-line functions and lower-level functions for large files.

Writing and Reading a Whole File

file_put_contents() writes a string to a file (creating it if needed). Add FILE_APPEND to add to the end instead of overwriting. file_get_contents() reads the whole file into a string.

<?php
file_put_contents('notes.txt', "First line\n");
file_put_contents('notes.txt', "Second line\n", FILE_APPEND);

echo file_get_contents('notes.txt');
echo filesize('notes.txt'), " bytes";
First line
Second line
23 bytes

Reading Line by Line With fopen

For large files, open a handle and read one line at a time so you do not load everything into memory.

<?php
$handle = fopen('notes.txt', 'r');
$n = 1;
while (($line = fgets($handle)) !== false) {
    echo $n++ . ": " . trim($line) . "\n";
}
fclose($handle);
1: First line
2: Second line

Working With CSV Files

<?php
$rows = [['name', 'city'], ['Usman', 'Lahore'], ['Mira', 'Dubai']];
$f = fopen('people.csv', 'w');
foreach ($rows as $row) {
    fputcsv($f, $row);
}
fclose($f);

$f = fopen('people.csv', 'r');
$header = fgetcsv($f);
while (($row = fgetcsv($f)) !== false) {
    $person = array_combine($header, $row);
    echo "{$person['name']} lives in {$person['city']}\n";
}
fclose($f);
Usman lives in Lahore
Mira lives in Dubai

File Modes and Checks

  • r: read only; w: write, truncating the file; a: append; x: create, fail if it exists
  • file_exists(), is_file(), is_dir() check paths
  • unlink() deletes a file, mkdir() creates a folder
  • Use __DIR__ to build paths relative to the current script

Handling PHP File Uploads

Uploaded files arrive in $_FILES. Check for errors, validate size and real MIME type, give the file a new random name, and store it outside the public folder when possible.

<?php
$file = $_FILES['avatar'] ?? null;
if ($file && $file['error'] === UPLOAD_ERR_OK) {
    $allowed = ['image/png' => 'png', 'image/jpeg' => 'jpg'];
    $mime = mime_content_type($file['tmp_name']);
    if (isset($allowed[$mime]) && $file['size'] < 2_000_000) {
        $name = bin2hex(random_bytes(8)) . '.' . $allowed[$mime];
        move_uploaded_file($file['tmp_name'], __DIR__ . "/uploads/$name");
        echo "Saved as $name";
    } else {
        echo "Invalid file";
    }
}
Saved as 3f9a1c0b7d2e4a68.png

Frequently asked questions

How do I read a file line by line in PHP?

Open it with fopen() and call fgets() in a while loop, or use file($path, FILE_IGNORE_NEW_LINES) for small files to get an array of lines.

How do I append to a file in PHP?

Use file_put_contents($path, $text, FILE_APPEND) or open it with fopen($path, "a").

Why is my PHP upload not working?

Check that the form has enctype="multipart/form-data", that upload_max_filesize and post_max_size in php.ini are large enough, and that the target folder is writable.