LearnContact
Lesson 3422 min read

File Handling

Learn how to read, write, and append to files on the server using PHP's built-in file functions.

Introduction

Not every piece of data belongs in a database. Configuration files, simple logs, cached results, and small text-based records are often easiest to manage as plain files sitting right on the server's disk. PHP has supported working with files since its earliest versions, and modern PHP makes the common cases — reading and writing an entire file — a single function call.

This lesson covers the everyday file functions you will reach for most often: file_get_contents(), file_put_contents(), and file_exists(), along with a brief look at the lower-level fopen() family for when you need more control.

What You Will Learn
  • How to read an entire file at once with file_get_contents().
  • How to write and append to a file with file_put_contents().
  • How to check whether a file exists before working with it.
  • A brief look at the lower-level fopen(), fgets(), and fclose() functions.
  • How to build a simple text-based log file that reads, appends, and reads again.

Checking If a File Exists

Before reading or writing a file, it is good practice to confirm it actually exists — especially for reading, since attempting to read a missing file triggers a warning. file_exists() returns true or false for a given path.

check.php
<?php
$path = "data/notes.txt";

if (file_exists($path)) {
    echo "The file exists.";
} else {
    echo "The file does not exist yet.";
}
?>
Example Output
The file does not exist yet.

Reading a File

file_get_contents() reads an entire file into a single string in one call — no loops, no manual opening or closing required. It is the simplest way to load a file's contents.

read.php
<?php
$content = file_get_contents("data/notes.txt");
echo $content;
?>
Example Output
Meeting notes: discuss project timeline.
Combine with file_exists()

Wrapping file_get_contents() in a file_exists() check avoids a warning if the file happens to be missing, letting your code handle that case gracefully.

Writing to a File

file_put_contents() writes a string to a file in one call. By default, it overwrites the file completely if it already exists, or creates it if it does not.

write.php
<?php
file_put_contents("data/notes.txt", "Meeting notes: discuss project timeline.");
echo "File saved.";
?>
Example Output
File saved.

Appending to a File

To add new content without erasing what is already there, pass the FILE_APPEND flag as a third argument. This is the pattern used for logs, where each new entry should be added to the end rather than replacing the whole file.

append.php
<?php
file_put_contents("data/notes.txt", "\nFollow-up: send meeting summary.", FILE_APPEND);
echo "Note appended.";
?>
Example Output
Note appended.
Watch the Flag

Forgetting FILE_APPEND is one of the most common file-handling mistakes — without it, file_put_contents() silently erases the file's previous contents.

A Lower-Level Alternative

For very large files, or when you need to process a file line by line instead of loading it all into memory, PHP also offers a lower-level trio: fopen() to open a file handle, fgets() to read one line at a time, and fclose() to close it when done. You will not need this often for small files, but it is worth recognizing.

lowlevel.php
<?php
$handle = fopen("data/notes.txt", "r");
while (($line = fgets($handle)) !== false) {
    echo $line;
}
fclose($handle);
?>
Example Output
Meeting notes: discuss project timeline.
Follow-up: send meeting summary.

Example: A Simple Log File

Here is a small worked example that checks whether a log file exists, appends a new timestamped entry to it, and then reads the whole file back to display it.

log-example.php
<?php
$logFile = "data/activity.log";

if (!file_exists($logFile)) {
    file_put_contents($logFile, "Log created.\n");
}

$entry = "[" . date("Y-m-d H:i:s") . "] User logged in.\n";
file_put_contents($logFile, $entry, FILE_APPEND);

echo file_get_contents($logFile);
?>
Example Output
Log created.
[2026-07-26 09:15:42] User logged in.

Common Mistakes

Avoid These Mistakes
  • Calling file_put_contents() without FILE_APPEND and accidentally erasing previous data.
  • Reading a file with file_get_contents() without first checking file_exists(), causing a warning.
  • Forgetting fclose() after using fopen(), leaving the file handle open.
  • Assuming the web server process has permission to write to every folder — file writes can fail silently if permissions are wrong.

Best Practices

  • Prefer file_get_contents() and file_put_contents() for simple, whole-file operations.
  • Reach for fopen()/fgets()/fclose() only when a file is too large to load entirely into memory.
  • Always check file_exists() before reading a file that might not be there yet.
  • Use FILE_APPEND deliberately whenever you want to add to a file instead of replacing it.
  • Store files that should never be publicly downloadable outside the web-accessible folder.

Frequently Asked Questions

Does file_put_contents() create the file if it does not exist?

Yes, as long as the containing folder exists and is writable, file_put_contents() will create a new file automatically.

What does file_get_contents() return if the file is missing?

It returns false and triggers a warning, which is why checking file_exists() first is good practice.

Can file_get_contents() read a file from a URL?

Yes, if allow_url_fopen is enabled in php.ini, file_get_contents() can fetch remote URLs too, though dedicated HTTP libraries are usually preferred for that.

Is file_put_contents() safe for concurrent writes from multiple visitors?

By default it is not fully safe under heavy concurrency; passing the LOCK_EX flag helps prevent two processes from writing at exactly the same time.

When should I use a database instead of a plain file?

Once data needs to be searched, filtered, updated concurrently by many users, or related to other data, a database is almost always the better choice.

Key Takeaways

  • file_get_contents() reads an entire file into a string in one call.
  • file_put_contents() writes a string to a file, overwriting it by default.
  • Passing FILE_APPEND as the third argument appends instead of overwriting.
  • file_exists() checks whether a file is present before you work with it.
  • fopen(), fgets(), and fclose() offer more control for line-by-line or large-file processing.

Summary

PHP's file functions make working with plain text files on the server straightforward: file_get_contents() and file_put_contents() cover most everyday needs, while the FILE_APPEND flag and file_exists() round out the common patterns for logs and simple records.

In this lesson, you learned to read, write, append to, and check for files, and built a small log file example. Next, you will learn how to store small pieces of data directly in a visitor's browser using cookies.

Lesson 34 Completed
  • You can read a file with file_get_contents().
  • You can write and append to a file with file_put_contents().
  • You know how to check for a file before using it.
  • You are ready to learn about cookies.
Next Lesson →

Cookies