Skip to main content
PHP for Beginners
CHAPTER 14 Beginner

PHP File Handling

Updated: May 12, 2026
25 min read

# Chapter 14: PHP File Handling

1. Introduction

Welcome to Chapter 14! Up until now, all the data we've used—variables, arrays, form submissions—exists only in the server's RAM (Memory). When the PHP script finishes running, that data vanishes instantly. To make an application useful, data must be saved permanently. The simplest way to do this, before jumping into databases, is using File Handling. In this chapter, we will learn how PHP can read text files, create new files, write data to them, and act as a simple persistent storage system.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Read the entire contents of a file instantly.
  • Open files in different modes (Read, Write, Append).
  • Write new data to text files.
  • Understand the importance of closing files.
  • Build a simple, database-free application.

3. Reading Files: The Easy Way

If you just want to grab the contents of a file and dump it into a variable, PHP provides a magical, one-line function: file_get_contents().
php
12345
<?php
// Reads 'story.txt' from the same folder
$story = file_get_contents("story.txt");
echo $story;
?>

*Note: If story.txt does not exist, PHP will throw a warning.*

4. Writing Files: The Easy Way

Similarly, if you want to completely overwrite a file (or create it if it doesn't exist) with new text, use file_put_contents().
php
12345
<?php
$data = "PHP is fun!";
// Creates 'data.txt' and writes the string to it
file_put_contents("data.txt", $data);
?>

5. Advanced File Handling (fopen, fwrite, fclose)

While the "easy ways" are great, sometimes you need precise control—like adding a single line to a 5GB log file without loading the whole 5GB into memory first. For this, we use the fopen() stream.

File Modes:

  • "r" (Read): Opens file for reading. File must exist.
  • "w" (Write): Opens file for writing. Erases all existing content. Creates file if it doesn't exist.
  • "a" (Append): Opens file for writing. Adds data to the *end* of the file without erasing old data. Creates file if it doesn't exist.

php
1234567891011121314
<?php
// 1. Open the file in Append mode
$file = fopen("log.txt", "a");

$log_entry = "User logged in at " . date("Y-m-d H:i:s") . "\n";

// 2. Write to the file
fwrite($file, $log_entry);

// 3. Close the file (Crucial for freeing up server memory!)
fclose($file);

echo "Log saved!";
?>

6. Reading Line by Line

If you have a file with thousands of usernames, you can read it line-by-line using a while loop and fgets().
php
123456789101112
<?php
$file = fopen("users.txt", "r");

// feof() checks if we have reached the End Of File
while (!feof($file)) {
    // fgets() reads exactly one line
    $line = fgets($file);
    echo $line . "<br>";
}

fclose($file);
?>

7. Real-World Examples

A common real-world use for file handling is a hit counter. Every time someone visits the page, PHP reads a number from a text file, adds 1, and saves it back.
php
12345678910111213141516171819
<?php
$file_path = "counter.txt";

// If file doesn't exist, start at 0
if (!file_exists($file_path)) {
    file_put_contents($file_path, 0);
}

// Read current count
$count = file_get_contents($file_path);

// Add 1
$count++;

// Save new count
file_put_contents($file_path, $count);

echo "You are visitor number: $count";
?>

8. Output Explanations

In the fopen append example, the \n character adds a newline (enter key) to the text file. Every time the script runs, a new timestamp is added to the bottom of log.txt, preserving all historical login data.

9. Common Mistakes

  • Permission Denied: On live servers (like Linux), PHP might not have permission to write files to the disk. You may need to change folder permissions (CHMOD 755 or 777 in extreme cases) via your host.
  • Forgetting fclose(): Leaving files open can cause memory leaks and lock the file, preventing other scripts from reading or writing to it.
  • Using "w" instead of "a": If you use "w" mode on your precious log file, it will delete years of logs instantly and replace them with the single new line.

10. Best Practices

  • Always use file_exists() before trying to open a file in "r" mode to prevent ugly server errors.
  • Use file_put_contents for simple operations, but use fopen/fwrite for massive files to save RAM.

11. Exercises

  1. 1. Use file_put_contents to create a file named secret.txt containing a hidden message.
  1. 2. Read the file using file_get_contents and echo it out.

12. Mini Project: Simple Notes App

Task: Build a form where a user can type a note. When submitted, append the note to a notes.txt file along with the date. Below the form, display all previously saved notes.
php
123456789101112131415161718192021222324252627282930313233343536373839404142
<?php
$file_path = "notes.txt";

// 1. Process new note submission
if ($_SERVER["REQUEST_METHOD"] == "POST" && !empty($_POST[&#039;note'])) {
    $note = htmlspecialchars($_POST[&#039;note']);
    $date = date("F j, Y, g:i a");
    
    // Format the entry
    $entry = "[$date] $note \n";
    
    // Append to file
    $file = fopen($file_path, "a");
    fwrite($file, $entry);
    fclose($file);
}
?>

<!DOCTYPE html>
<html>
<head><title>Notes App</title></head>
<body>
    <h2>Add a Note</h2>
    <form action="" method="POST">
        <input type="text" name="note" placeholder="Type a note..." required>
        <button type="submit">Save</button>
    </form>

    <hr>
    <h2>Saved Notes</h2>
    <pre>
<?php
// 2. Display existing notes
if (file_exists($file_path)) {
    echo file_get_contents($file_path);
} else {
    echo "No notes saved yet.";
}
?>
    </pre>
</body>
</html>

13. Coding Challenges

Challenge 1: Create an array of 3 names. Use a foreach loop and file_put_contents with the FILE_APPEND flag (Research this flag!) to write them into a names.txt file, each on a new line.

14. MCQs with Answers

1. Which mode opens a file for writing, but adds data to the end without erasing it? A) "r" B) "w" C) "a" D) "x" *Answer: C*

2. Which function grabs the entire contents of a file in one line of code? A) fopen() B) file_get_contents() C) read_file() D) fgets() *Answer: B*

3. Why is fclose() important? A) It encrypts the file. B) It sends the file to the browser. C) It frees up server memory and removes the lock on the file. D) It deletes the file. *Answer: C*

15. Interview Questions

Q: When would you use fopen/fgets over file_get_contents? *A:* file_get_contents loads the entire file into the server's RAM at once. This is fine for small files. However, if you are reading a 2GB log file, file_get_contents will crash the server by exceeding the PHP memory limit. Using fopen and fgets inside a loop allows you to process the file one line at a time, using almost zero RAM.

Q: How do you prevent errors if a file doesn't exist before reading it? *A:* You should wrap your read logic inside an if (file_exists('filename.txt')) conditional block.

16. FAQs

Q: Can I save arrays to a text file? *A:* You cannot save a raw PHP array to a text file. You must first convert it into a String. The most common way is converting it to a JSON string using json_encode(), which we will cover in Chapter 27!

17. Summary

Data is now permanent! You learned how to bypass RAM and write data directly to the server's hard drive using file_put_contents and the fopen/fwrite stream. You understand the critical differences between Write (w) mode and Append (a) mode, and successfully built a database-free persistent Notes application.

18. Next Chapter Recommendation

File handling is great for data, but what about code files? Copying your website's navigation bar HTML into 50 different pages is a nightmare to update. In Chapter 15: PHP Include and Require, we will learn how to inject PHP files into other PHP files to create reusable page layouts!

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·