๐Ÿ“ Web Development

PHP File Handling: Read, Write and Delete Files

Aug 30, 20265 min read5 viewsBy Flow

PHP file handling is how your script reads and writes files on the server โ€” a log, a small data file, an exported CSV. Everything up to now lived in memory and vanished when the script finished. A file is the simplest way to make something last without setting up a whole database.

Two functions do most of the work

Before the older, fiddlier way, meet the two you will reach for ninety per cent of the time. file_put_contents() writes a whole string to a file, and file_get_contents() reads a whole file back into a string.

<?php
$text = "Hello from PHP.\nThis file was written by file_put_contents.";

file_put_contents("notes.txt", $text);

echo "Wrote " . strlen($text) . " bytes to notes.txt";
?>

Output

PHP file handling output confirming file_put_contents wrote 59 bytes to notes.txt

Run that and a file called notes.txt appears next to your script. If it already existed, its contents are replaced โ€” file_put_contents() overwrites by default, which is worth remembering before you point it at something important.

The path is relative to the script. "notes.txt" means "in the same folder". You can also give a full path like "C:/data/notes.txt".

Reading it back

<?php
$content = file_get_contents("notes.txt");

echo nl2br($content);
?>

Output

PHP file handling output reading notes.txt back with file_get_contents across two lines

The whole file comes back as one string. The \n we wrote is a real newline, but a browser ignores newlines in HTML โ€” that is what nl2br() is for. It turns each newline into a <br> so the two lines actually show as two lines.

Appending instead of overwriting

Overwriting is usually wrong for something like a log โ€” you want to add to the end, not wipe it. Pass the FILE_APPEND flag.

<?php
file_put_contents("notes.txt", "\nA third line, added later.", FILE_APPEND);

echo nl2br(file_get_contents("notes.txt"));
?>

Output

PHP file handling output showing a third line appended with FILE_APPEND

Same function, one extra argument, completely different behaviour. Without FILE_APPEND the file would now contain only the new line. With it, the line joins what was already there.

Reading a file line by line

file_get_contents() loads the entire file into memory at once. Fine for a small notes file, a bad idea for a two-gigabyte log. When the file is large, or you only need to look at each line in turn, open a handle and read one line at a time.

<?php
$handle = fopen("notes.txt", "r");

$number = 1;

while (($line = fgets($handle)) !== false) {
    echo $number . ": " . htmlspecialchars(rtrim($line)) . "<br>";
    $number++;
}

fclose($handle);
?>

Output

PHP file handling output reading notes.txt line by line and numbering each with fgets

This is the older, more manual style. fopen() opens the file and returns a handle, fgets() pulls one line each time round the loop, and fclose() lets the file go at the end. The loop ends when fgets() returns false, which happens at the end of the file.

The "r" is the mode โ€” read. It is the first of a small set worth knowing:

ModeMeans
rRead. The file must already exist.
wWrite, wiping anything already there.
aAppend, keeping what is there and adding to the end.
xWrite, but fail if the file already exists.

Add a + to any of them for read-and-write, but you rarely need it starting out. Almost all PHP file handling comes down to picking the right mode and letting these functions do the rest.

Does it exist, and deleting it

Trying to read a file that is not there is an error. Check first with file_exists(), and remove a file with unlink() โ€” an oddly named function, but that is the one.

<?php
if (file_exists("notes.txt")) {
    echo "notes.txt exists, " . filesize("notes.txt") . " bytes<br>";

    unlink("notes.txt");

    echo "Deleted it.";
} else {
    echo "notes.txt is not there.";
}
?>

Output

PHP file handling output reporting the file size then deleting it with unlink

unlink() deletes immediately and permanently. There is no recycle bin. Run this and notes.txt is gone โ€” if you want it back, run the first example again to recreate it.

A practical one: writing and reading a CSV

Putting it together with something you will actually do โ€” save rows of data as a CSV and read them back. PHP has two functions built for exactly this, so you never have to worry about commas inside values or quoting.

<?php
$rows = [
    ["Ali", 82],
    ["Sara", 91],
    ["Bilal", 68],
];

$handle = fopen("marks.csv", "w");
foreach ($rows as $row) {
    fputcsv($handle, $row);
}
fclose($handle);

$handle = fopen("marks.csv", "r");
while (($row = fgetcsv($handle)) !== false) {
    echo $row[0] . " scored " . $row[1] . "<br>";
}
fclose($handle);

unlink("marks.csv");
?>

Output

PHP file handling output writing and reading a CSV of student marks with fputcsv and fgetcsv

fputcsv() writes one array as one CSV row, handling the commas and quotes for you. fgetcsv() reads one row back into an array. Between them they are the easy way to move tabular data in and out of a file, and the file it produces opens straight in Excel.

Three mistakes with PHP file handling

Forgetting that w and file_put_contents() overwrite. Both wipe the file unless you ask for append. Reach for FILE_APPEND or mode a when you mean to add.

Not checking the file exists. Reading a missing file warns and gives you nothing. Guard reads with file_exists() when the file might not be there.

Trusting a filename that came from a user. Never build a path straight from user input โ€” fopen("uploads/" . $_GET["name"]) lets someone request ../../config.php. That is path traversal, and it matters the moment a real visitor is involved.

Common questions about PHP file handling

The questions that come up most once scripts start touching real files.

What is the difference between file_put_contents and fwrite?

file_put_contents() writes a whole string in one call and closes the file for you. fwrite() works with an open handle from fopen(), so you can write in stages. For most jobs file_put_contents() is shorter and does the same thing.

How do I append to a file instead of overwriting in PHP?

Pass the FILE_APPEND flag to file_put_contents(), or open the file with fopen() in mode a. Both keep the existing contents and add to the end. The default is to overwrite.

Why does file_get_contents return false or warn?

Usually the file does not exist, the path is wrong, or the script does not have permission to read it. Remember the path is relative to the script's own folder unless you give an absolute one. Check with file_exists() first.

How do I delete a file in PHP?

unlink("path/to/file"). It is permanent and immediate โ€” there is no undo โ€” so confirm the file exists and is the right one before calling it.

Should I use a file or a database to store data in PHP?

A file is fine for small, simple things โ€” a log, a config, a cache. The moment you need to search, sort, or have several users writing at once, use a database. That crossover is exactly what PHP MySQL is for.

What is next

You can now read and write files on the server. The most common reason a beginner needs that is to accept a file from a visitor โ€” a profile picture, a document โ€” and that has its own rules and its own risks.

That is uploads, and it is the next lesson: PHP file upload. It builds directly on PHP forms, so a quick look back there will not hurt.

Comments

Loading comments...

Link copied to clipboard