PHP File Open / Read / Close
📂 PHP File Open / Read / Close
In PHP, file handling allows you to open, read, write, and close files stored on the server.
This is very important for logs, configuration files, data storage, and real-world applications.
1️⃣ What is File Handling in PHP?
File handling in PHP means:
-
Opening a file
-
Reading data from it
-
Writing data to it
-
Closing the file
📌 PHP provides built-in functions for file handling.
2️⃣ File Open – fopen() ⭐
Syntax
Common File Modes
| Mode | Meaning |
|---|---|
r |
Read only (file must exist) |
w |
Write only (creates/overwrites) |
a |
Append (adds data at end) |
r+ |
Read & write |
w+ |
Read & write (overwrite) |
a+ |
Read & append |
Example: Open a File
3️⃣ File Read – fread() ⭐
Syntax
Example: Read Entire File
✔ Reads full content of the file
4️⃣ Read File Line by Line – fgets() ⭐
✔ Very useful for large files
5️⃣ Read File Character by Character – fgetc()
6️⃣ File Close – fclose() ⭐
Syntax
Why Close a File?
✔ Frees server memory
✔ Prevents file corruption
✔ Good programming practice
📌 Always close files after use.
7️⃣ Shortcut Functions (Very Common)
file_get_contents() ⭐
Reads entire file in one line.
readfile()
Reads and outputs file directly.
8️⃣ File Exists Check – file_exists()
✔ Avoids runtime errors
9️⃣ Error Handling with Files ⭐
🔟 Common Mistakes ❌
❌ Forgetting to close file
❌ Using wrong file mode
❌ Not checking file existence
❌ Reading large files with fread()
📌 Interview Questions & MCQs (Very Important)
Q1. Which function opens a file in PHP?
A) open()
B) file()
C) fopen()
D) read()
✅ Answer: C
Q2. Which mode opens a file for reading only?
A) w
B) a
C) r
D) x
✅ Answer: C
Q3. Which function reads a file line by line?
A) fread()
B) fgets()
C) fgetc()
D) readfile()
✅ Answer: B
Q4. Which function closes a file?
A) close()
B) stop()
C) end()
D) fclose()
✅ Answer: D
Q5. Which function reads entire file easily?
A) fread()
B) file_get_contents()
C) fgets()
D) fopen()
✅ Answer: B
Q6. Why is fclose() important?
A) Speeds PHP
B) Frees memory
C) Prevents corruption
D) All of the above
✅ Answer: D
🔥 Real-Life Use Cases
✔ Reading configuration files
✔ Displaying text files
✔ Logging user activity
✔ File-based data storage
✅ Summary
-
fopen()→ open file -
fread(),fgets(),fgetc()→ read file -
fclose()→ close file -
Always check file existence
-
Use shortcut functions for simplicity
-
Very important for PHP exams & interviews
