TExcelTAD
Home › PHP › PHP File Handling

PHP File Handling

PHP can create, read, change and delete files on the server. You use it for log files, CSV exports, uploaded images, caches and simple data storage. The playgrounds on this site have a small private folder, so every example below really writes files — and tidies up after itself with unlink().

The quick way: whole-file functions

For small files, two functions do everything in one call:

Function What it does
file_put_contents($name, $data) Writes a string to a file (creates or overwrites it); returns bytes written
file_put_contents($name, $data, FILE_APPEND) Adds to the end instead of overwriting
file_get_contents($name) Reads the whole file into a string
file($name, FILE_IGNORE_NEW_LINES) Reads the file into an array, one element per line
file_exists($name) true if the file (or folder) exists
filesize($name) Size in bytes
unlink($name) Deletes the file
php · try it yourself
<?php
$file = 'notes.txt';

$bytes = file_put_contents($file, "Buy milk\n");
echo "Wrote $bytes bytes" . PHP_EOL;

file_put_contents($file, "Learn PHP\n", FILE_APPEND);
file_put_contents($file, "Call Minh\n", FILE_APPEND);

echo file_get_contents($file);

$lines = file($file, FILE_IGNORE_NEW_LINES);
echo "Line count: " . count($lines) . ", second line: {$lines[1]}" . PHP_EOL;

unlink($file);
var_dump(file_exists($file));
Wrote 9 bytes
Buy milk
Learn PHP
Call Minh
Line count: 3, second line: Learn PHP
bool(false)

The classic way: fopen, fwrite, fgets, fclose

For large files, or when you want to process a file line by line without loading it all into memory, open a file handle with fopen(). The second argument is the mode:

Mode Meaning Pointer starts at Creates file? Truncates?
r read only start no no
r+ read and write start no no
w write only start yes yes
a append (write at end) end yes no
x create new, write only start fails if it exists –
c write, don't truncate start yes no
php · try it yourself
<?php
$fh = fopen('log.txt', 'w');
fwrite($fh, "2025-03-14 login ok\n");
fwrite($fh, "2025-03-14 upload failed\n");
fwrite($fh, "2025-03-15 login ok\n");
fclose($fh);

$fh = fopen('log.txt', 'r');
$n = 0;
while (($line = fgets($fh)) !== false) {
    $n++;
    if (str_contains($line, 'failed')) {
        echo "Problem on line $n: " . trim($line) . PHP_EOL;
    }
}
var_dump(feof($fh));
fclose($fh);

unlink('log.txt');
Problem on line 2: 2025-03-14 upload failed
bool(true)

fgets() returns one line (including its \n) each call and false at the end of the file; feof() tells you whether the pointer has reached the end.

Tip: Always fclose() handles you open. PHP closes them when the script ends, but long-running scripts can run out of handles.

CSV files

Spreadsheet data is often exchanged as CSV. fputcsv() writes an array as one correctly quoted line and fgetcsv() reads it back:

php · try it yourself
<?php
$rows = [
    ['product', 'price', 'note'],
    ['Green tea', '3.50', 'loose leaf'],
    ['Coffee, dark', '7.25', 'contains a comma'],
];

$fh = fopen('products.csv', 'w');
foreach ($rows as $row) {
    fputcsv($fh, $row, ',', '"', '');
}
fclose($fh);

echo file_get_contents('products.csv');
echo "---" . PHP_EOL;

$fh = fopen('products.csv', 'r');
$header = fgetcsv($fh, null, ',', '"', '');
while (($row = fgetcsv($fh, null, ',', '"', '')) !== false) {
    $item = array_combine($header, $row);
    echo "{$item['product']} costs {$item['price']}" . PHP_EOL;
}
fclose($fh);
unlink('products.csv');
product,price,note
"Green tea",3.50,"loose leaf"
"Coffee, dark",7.25,"contains a comma"
---
Green tea costs 3.50
Coffee, dark costs 7.25

Note: Since PHP 8.4, omitting the $escape argument of the CSV functions is deprecated. Passing '' (as above) disables the old non-standard escape character and silences the deprecation.

Checking before you act

Reading a file that does not exist produces a warning and returns false. Check first, and handle the failure yourself:

php · try it yourself
<?php
$name = 'missing.txt';

if (!file_exists($name)) {
    echo "$name does not exist yet - creating it" . PHP_EOL;
    file_put_contents($name, 'first version');
}

echo "Size: " . filesize($name) . " bytes" . PHP_EOL;
echo "Readable: " . (is_readable($name) ? 'yes' : 'no') . PHP_EOL;

rename($name, 'renamed.txt');
echo "After rename, old exists? " . var_export(file_exists($name), true) . PHP_EOL;

copy('renamed.txt', 'backup.txt');
echo "Backup says: " . file_get_contents('backup.txt') . PHP_EOL;

unlink('renamed.txt');
unlink('backup.txt');
missing.txt does not exist yet - creating it
Size: 13 bytes
Readable: yes
After rename, old exists? false
Backup says: first version

Uploaded files (concept)

When a form uses enctype="multipart/form-data" and an <input type="file">, PHP stores the upload in a temporary location and describes it in $_FILES. You then move it somewhere permanent:

php
<?php
$upload = $_FILES['avatar'];
if ($upload['error'] === UPLOAD_ERR_OK && $upload['size'] < 2_000_000) {
    $ext = pathinfo($upload['name'], PATHINFO_EXTENSION);
    move_uploaded_file($upload['tmp_name'], __DIR__ . "/uploads/" . bin2hex(random_bytes(8)) . ".$ext");
}

Never trust the original file name or type sent by the browser — generate your own name and check the content.

Test yourself

Which fopen() mode erases the existing content of a file?

  1. r
  2. a
  3. w
  4. c

How do you add a line to the end of a file without overwriting it, in one call?

  1. file_put_contents($f, $line, FILE_APPEND)
  2. file_get_contents($f, $line)
  3. fwrite($f, $line)
  4. file($f, FILE_APPEND)

What does fgets() return when it reaches the end of the file?

  1. An empty string
  2. null
  3. false
  4. -1