๐Ÿ“‚ PHP File Handling
Estimated reading: 4 minutes 27 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