PHP File Handling: A Comprehensive Guide
Learn how to read, write, and manipulate files in PHP using practical examples and modern best practices.
📖 1. Outputting a File with readfile()
The readfile() function reads a file and writes it directly to the output buffer. It is useful when you just want to output the contents of a file directly to the browser without modifying it.
Example
<?php
// Reads and outputs the content of webdictionary.txt
echo readfile("webdictionary.txt");
?>
📂 2. Opening and Closing a File
For more control, use fopen() and fclose(). fopen() provides various modes such as r (read), w (write), and a (append). Always close files after you are done.
<?php
// Open a file for reading
$file = fopen("webdictionary.txt", "r") or die("Unable to open file!");
// Do some file operations...
// Always close the file to free up resources
fclose($file);
?>
🔍 3. Reading File Contents
Using fread(), you can read from an open file. You must pass the file pointer and the maximum length (in bytes) to read.
<?php
$file = fopen("webdictionary.txt", "r") or die("Unable to open file!");
// Read the complete file using filesize()
echo fread($file, filesize("webdictionary.txt"));
fclose($file);
?>
✍️ 4. Writing to a File
Using fwrite(), you can write data to a file. Be careful with mode w, as it will overwrite the file. Use mode a if you wish to append without deleting existing content.
<?php
$file = fopen("newfile.txt", "w") or die("Unable to open file!");
$txt = "John Doe\n";
fwrite($file, $txt);
$txt = "Jane Doe\n";
fwrite($file, $txt);
fclose($file);
?>