PHP File Handling
File handling is an important part of any web application. PHP has several functions for creating, reading, uploading, and editing files.
Warning: Be careful when manipulating files. You can do a lot of damage if you make a mistake (e.g., accidentally overwriting a critical system file).
1. The readfile() Function
The readfile() function is the simplest way to read a file and write it to the output buffer.
<?php
echo readfile("webdictionary.txt");
?>
2. Open, Read, and Close Files
For better control, we use fopen(), fread(), and fclose().
Opening a File: fopen()
The first parameter contains the name of the file to be opened and the second parameter specifies in which mode the file should be opened.
<?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
echo fread($myfile, filesize("webdictionary.txt"));
fclose($myfile);
?>
3. File Modes
Common modes used in fopen():
- r: Open for read only. Starting at the beginning of the file.
- w: Open for write only. Erases the contents of the file or creates a new file if it doesn't exist.
- a: Open for write only. The existing data in the file is preserved (Append).
- x: Creates a new file for write only. Returns
FALSE if file already exists.
4. Reading a Single Line: fgets()
The fgets() function is used to read a single line from a file.
<?php
$myfile = fopen("webdictionary.txt", "r");
echo fgets($myfile);
fclose($myfile);
?>
5. Check End-of-File: feof()
The feof() function checks if the "end-of-file" (EOF) has been reached. This is useful for looping through data of unknown length.
<?php
$myfile = fopen("webdictionary.txt", "r");
while(!feof($myfile)) {
echo fgets($myfile) . "<br>";
}
fclose($myfile);
?>
Best Practice: Always use fclose() after you are done with a file. It is good programming practice to not leave open files running on your server, as they consume resources.