How to Open Read and Close Files in PHP with fopen
Working with files is a fundamental aspect of PHP development. This
article provides a quick and practical guide on how to open, read, and
close files in PHP using the built-in fopen(),
fread(), and fclose() functions, complete with
clear code examples.
Opening a File with fopen()
To work with a file in PHP, you must first open it using the
fopen() function. This function requires two primary
arguments: the file path and the mode in which you want to open the
file. It returns a file pointer resource on success, or
FALSE on failure.
The most common mode for reading is 'r', which opens the
file for reading only and places the file pointer at the beginning of
the file.
$filename = "example.txt";
$file = fopen($filename, "r");
if (!$file) {
die("Failed to open the file.");
}Reading the File
Once the file is successfully opened, you can read its content. There are two primary methods to read an open file resource:
Method 1: Reading the Entire File with fread()
The fread() function reads from an open file pointer. It
requires the file handle and the maximum number of bytes to read. To
read the entire file, use the filesize() function to
specify the length.
$content = fread($file, filesize($filename));
echo $content;Method 2: Reading Line-by-Line with fgets()
For larger files, reading the entire file into memory at once may not
be efficient. Instead, you can use fgets() inside a
while loop to read the file line-by-line until you reach
the end of the file (feof()).
while (!feof($file)) {
$line = fgets($file);
echo $line . "<br>";
}Closing the File with fclose()
After you have finished reading the file, you must close it using the
fclose() function. Closing the file resource is a best
practice that frees up system memory and prevents file locking
issues.
fclose($file);Complete Code Example
Below is a complete, ready-to-run PHP script that combines the opening, reading, and closing processes:
$filename = "example.txt";
// 1. Open the file in read-only mode
$file = fopen($filename, "r");
if ($file) {
// 2. Read the entire content of the file
$content = fread($file, filesize($filename));
echo $content;
// 3. Close the file resource
fclose($file);
} else {
echo "Error: Unable to open the specified file.";
}