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

PHP File Handling Introduction

File handling lets PHP open, read, and write files on the server, like opening a notebook to read or add notes. It is how a program remembers things after it finishes.
Syntax
php
$handle = fopen("filename.txt", "mode");   // false on failure
fwrite($handle, $data);
fclose($handle);

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
// Declare `$handle`, set to `fopen("data.txt", "w")`
$handle = fopen("data.txt", "w");
// Check whether `$handle`
if ($handle) {
    // Print "File opened successfully" to the output
    echo "File opened successfully";
    // Call `fclose($handle)`
    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
// Declare `$handle`, set to `fopen("data.txt", "w")`
$handle = fopen("data.txt", "w");
// Call `fwrite($handle, "Hello, file!")`
fwrite($handle, "Hello, file!");
// Call `fclose($handle)`
fclose($handle);
// Print `file_get_contents("data.txt")` to the output
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
// Declare `$handle`, set to `fopen("data.txt", "w")`
$handle = fopen("data.txt", "w");
// Check whether `$handle === false`
if ($handle === false) {
    // Print "Failed to open file" to the output
    echo "Failed to open file";
// Otherwise, run this branch
} else {
    // Call `fwrite($handle, "Saved data")`
    fwrite($handle, "Saved data");
    // Call `fclose($handle)`
    fclose($handle);
    // Print "File written and closed" to the output
    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
// Call `file_put_contents("data.txt", "sample")`
file_put_contents("data.txt", "sample");
// Check whether `file_exists("data.txt") && is_writable("data.txt")`
if (file_exists("data.txt") && is_writable("data.txt")) {
    // Print "File exists and is writable" to the output
    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
// Call `file_put_contents("temp.txt", "temporary data")`
file_put_contents("temp.txt", "temporary data");
// Print `file_get_contents("temp.txt") . "\n"` to the output
echo file_get_contents("temp.txt") . "\n";
// Call `unlink("temp.txt")`
unlink("temp.txt");
// Print `file_exists("temp.txt") ? "Still exists" : "Deleted successfully"` to the output
echo file_exists("temp.txt") ? "Still exists" : "Deleted successfully";
?>
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Not checking whether fopen returned false before using the handle.
  2. Forgetting fclose, so buffered data may not be written.
  3. Using the wrong mode, such as w, which erases an existing file.
🔒

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.