PHP File Handling
# 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().
*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, usefile_put_contents().
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 thefopen() 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.
6. Reading Line by Line
If you have a file with thousands of usernames, you can read it line-by-line using awhile loop and fgets().
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.8. Output Explanations
In thefopen 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_contentsfor simple operations, but usefopen/fwritefor massive files to save RAM.
11. Exercises
-
1.
Use
file_put_contentsto create a file namedsecret.txtcontaining a hidden message.
-
2.
Read the file using
file_get_contentsand 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 anotes.txt file along with the date. Below the form, display all previously saved notes.
13. Coding Challenges
Challenge 1: Create an array of 3 names. Use aforeach 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 usefopen/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 usingjson_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 usingfile_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.