File handling is an important part of any web application. You often need to open and process a file for different tasks, such as reading configuration data, parsing logs, or importing user lists.
PHP has several powerful functions for creating, reading, uploading, and editing files.
The readfile() function reads a file and writes it to the output buffer. This is the simplest way to display the contents of a file on a webpage.
<?php
echo readfile("dictionary.txt");
?>
The readfile() function is useful if all you want to do is open up a file and read its contents. But for more advanced manipulation, you need the fopen() function.
A better method for opening files is with the fopen() function. This function gives you more options than the readfile() function.
The first parameter of fopen() contains the name of the file to be opened, and the second parameter specifies in which mode the file should be opened.
Common Modes:
r: Open a file for read only.w: Open a file for write only. Erases the contents of the file or creates a new file if it doesn't exist.a: Open a file for write only. Appends (adds) data to the end of the file.
<?php
$myfile = fopen("webdict.txt", "r") or die("Unable to open file!");
// Read the file entirely
echo fread($myfile, filesize("webdict.txt"));
// Always close the file when you're done!
fclose($myfile);
?>
Important: The fclose() function is used to close an open file. It is a good programming practice to close all files after you have finished with them to free up server memory.
Which mode should you use with fopen() if you only want to read the file?