← Back to PHP Course | Chapter 9: File Handling | Lesson 1 of 8

PHP File Handling Introduction

Opening Files with fopen()

PHP can read from and write to files on the server's filesystem, letting a script persist data, log activity, or generate downloadable content without needing a database for every task.

Example: Opening Files with fopen()

php
<?php
$handle = fopen("data.txt", "w");
if ($handle) {
    echo "File opened successfully";
    fclose($handle);
}
?>

Writing Files with fwrite()

File operations in PHP revolve around a small set of core functions — fopen(), fread()/fwrite(), and fclose() — that mirror the open-use-close pattern found in most programming languages' file APIs.

Example: Writing Files with fwrite()

php
<?php
$handle = fopen("data.txt", "w");
fwrite($handle, "Hello, file!");
fclose($handle);
echo file_get_contents("data.txt");
?>

Closing Files with fclose()

Always check whether a file operation succeeded, since fopen() returns false (not an exception) on failure by default, and code that assumes success will produce confusing errors further down the line.

Example: Closing Files with fclose()

php
<?php
$handle = fopen("data.txt", "w");
if ($handle === false) {
    echo "Failed to open file";
} else {
    fwrite($handle, "Saved data");
    fclose($handle);
    echo "File written and closed";
}
?>

Checking File Existence

File permissions and paths matter a lot in real deployments: PHP's process needs OS-level permission to read or write a given path, and a misconfigured permission is one of the most common file-handling bugs in production.

Example: Checking File Existence

php
<?php
file_put_contents("data.txt", "sample");
if (file_exists("data.txt") && is_writable("data.txt")) {
    echo "File exists and is writable";
}
?>

Deleting Files with unlink()

Beyond the low-level functions, PHP offers convenience wrappers like file_get_contents() and file_put_contents() that handle the open/read-or-write/close sequence in a single call for simple cases.

Example: Deleting Files with unlink()

php
<?php
file_put_contents("temp.txt", "temporary data");
echo file_get_contents("temp.txt") . "\n";
unlink("temp.txt");
echo file_exists("temp.txt") ? "Still exists" : "Deleted successfully";
?>
🔒

Chapter Quiz — Complete all 8 topics to unlock

0/8 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.