📂 PHP File Handling
Estimated reading: 4 minutes 43 views

📖 PHP Open / Read / Write / Append – Perform File I/O Operations in PHP

Learn how to open, read, write, and append data to files in PHP using built-in functions like fopen(), fwrite(), and fread().


🧲 Introduction – Why File I/O Is Essential in PHP

PHP’s file handling functions allow your scripts to interact with the filesystem, enabling you to store logs, process data, manage uploads, and maintain configuration files. Understanding how to open and manipulate files safely is key to dynamic web applications.

🎯 In this guide, you’ll learn:

  • How to open files in various modes
  • How to read and write file content
  • The difference between write and append operations
  • Best practices for file I/O

📂 1. Opening Files with fopen()

$file = fopen("example.txt", "r");

➡️ fopen() opens a file and returns a file handle.
➡️ It takes the filename and a mode as arguments.


📄 2. File Open Modes

ModeDescription
rRead only; file must exist
wWrite only; truncate or create file
aAppend only; file pointer at the end
xCreate new file; error if file exists
r+Read/write; file must exist
w+Read/write; truncate or create file
a+Read/write; file pointer at end
x+Read/write; create new file

📘 Always check whether the file exists before using destructive modes (w, x, etc.).


📖 3. Reading Files with fread() or file_get_contents()

$file = fopen("example.txt", "r");
$content = fread($file, filesize("example.txt"));
fclose($file);

echo $content;

➡️ fread() reads a file of a specific length (in bytes).
➡️ filesize() helps determine how much to read.

✅ Shortcut: file_get_contents()

$content = file_get_contents("example.txt");

➡️ Reads the entire file into a string in one line.


✍️ 4. Writing to Files with fwrite()

$file = fopen("log.txt", "w");
fwrite($file, "New log entry\n");
fclose($file);

➡️ fwrite() writes content to the file.
➡️ Mode "w" overwrites existing content.


➕ 5. Appending to Files

$file = fopen("log.txt", "a");
fwrite($file, "Appended entry at " . date("H:i:s") . "\n");
fclose($file);

➡️ Mode "a" writes data at the end of the file.
➡️ Great for adding new entries without deleting old content.


🚫 6. Check Before File Operations

if (file_exists("notes.txt")) {
    $file = fopen("notes.txt", "r");
    // ...
}

➡️ Always verify the file’s existence before reading or writing.
➡️ Prevents warnings or errors during runtime.


🔐 7. File Permission Considerations

Ensure PHP has permission to access or modify the file:

  • ✅ Use chmod() to set permissions (e.g., 0644)
  • ✅ On Linux, directories should have at least 0755 permission
  • ✅ For web-based file uploads, use safe directories like /uploads/

🧠 Best Practices

  • ✅ Always call fclose() after using fopen()
  • ✅ Use "a" for logging and "w" for overwriting
  • ✅ Prefer file_get_contents() for small reads
  • ✅ Check file_exists() and is_writable() before operations
  • ❌ Never write to system or configuration files directly

📌 Summary – Recap & Next Steps

PHP offers multiple methods to read, write, and append files — making it easy to store and manage data persistently on the server.

🔍 Key Takeaways:

  • Use fopen() with the right mode (r, w, a, etc.)
  • Use fread() or file_get_contents() to read file contents
  • Use fwrite() for writing and "a" mode to append safely
  • Always check file permissions and close handles after operations

⚙️ Real-World Use Cases:
Logging user activity, writing data exports, reading configuration files, creating chat logs.


❓ Frequently Asked Questions (FAQs)

❓ What’s the difference between w and a modes?
"w" truncates (overwrites) the file; "a" appends data to the end.

❓ Should I always close the file with fclose()?
✅ Yes — it frees system resources and ensures data integrity.

❓ Can I read and write in the same session?
✅ Use modes like "r+", "w+", or "a+" to support both reading and writing.

❓ Is file_put_contents() better than fwrite()?
✅ For simple one-line writes, yes. It combines fopen(), fwrite(), and fclose().

file_put_contents("log.txt", "Hello World\n", FILE_APPEND);

Share Now :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

📖 PHP Open / Read / Write / Append

Or Copy Link

CONTENTS
Scroll to Top