PHP File Open / Read / Close
PHP File Open / Read / Close Tutorial
PHP allows you to open a file, read its contents, and then close the file using built-in functions. This is essential for processing files safely and efficiently.
1️⃣ Open a File (fopen)
The fopen() function opens a file in a specified mode:
Common Modes in fopen()
| Mode | Description |
|---|---|
r |
Read only (file must exist) |
w |
Write only (creates file or truncates existing) |
a |
Append only (creates file if not exists) |
r+ |
Read and write |
w+ |
Read and write (truncate if exists) |
a+ |
Read and append |
2️⃣ Read the File (fread)
Use fread() to read the contents of a file:
✅ filesize() returns the size of the file in bytes.
3️⃣ Read the File Line by Line (fgets)
fgets() reads one line at a time:
-
feof()checks for end-of-file. -
Useful for large files to avoid memory issues.
4️⃣ Close the File (fclose)
Always close files after processing to free system resources:
5️⃣ Alternative: file() Function
You can also read the entire file into an array without manually opening/closing:
✅ file() automatically opens, reads, and closes the file.
🏁 Summary
-
fopen()→ Open a file in a specified mode -
fread()→ Read the file content -
fgets()→ Read file line by line -
fclose()→ Close the file -
file()→ Read file into an array (shortcut) -
Always close files after usage to free resources.
