fopen() / fread() / fwrite() / fclose() Since: PHP 4(2000)
Opens a file as a stream, allowing you to read or write data line by line or byte by byte. Useful for memory-efficient sequential processing of large files, such as appending to logs.
Syntax
// Opens a file and returns a stream resource. $fp = fopen($filename, $mode); // Reads the specified number of bytes. fread($fp, $length); // Reads one line. fgets($fp, $length); // Writes a string. fwrite($fp, $string, $length); // Checks whether the end of the file has been reached. feof($fp); // Closes the file. fclose($fp);
Function Reference
| Function | Description |
|---|---|
| fopen($filename, $mode) | Opens a file in the specified mode. Returns a stream resource on success, or false on failure. |
| fread($fp, $length) | Reads the specified number of bytes from the stream. If the end of the file is reached, returns only the bytes read so far. |
| fgets($fp, $length) | Reads one line from the stream, including the newline character. Returns false at the end of the file. |
| fwrite($fp, $string) | Writes a string to the stream. Returns the number of bytes written, or false on failure. |
| feof($fp) | Returns true if the file pointer has reached the end of the file. |
| fclose($fp) | Closes the stream resource. Returns true on success. |
Common Open Modes
| Mode | Description |
|---|---|
| "r" | Read-only. The file pointer is placed at the beginning of the file. |
| "w" | Write-only. Truncates the file to zero length and writes from the beginning. Creates the file if it does not exist. |
| "a" | Append-only. Writes to the end of the file. Creates the file if it does not exist. |
| "r+" | Read and write. The file pointer is placed at the beginning of the file. |
| "w+" | Read and write. Truncates the file to zero length and writes from the beginning. |
| "a+" | Read and write. All writes go to the end of the file. |
Sample Code
<?php
// Open a file and read it line by line.
$fp = fopen("/var/www/html/data.txt", "r");
if ($fp === false) {
die("Could not open the file.");
}
while (!feof($fp)) {
$line = fgets($fp);
if ($line !== false) {
echo $line; // Each line is printed.
}
}
fclose($fp);
// Read a specific number of bytes with fread().
$fp = fopen("/var/www/html/data.bin", "r");
$header = fread($fp, 4); // Read the first 4 bytes.
echo bin2hex($header); // Print the binary data as hexadecimal.
fclose($fp);
// Write to a file.
$fp = fopen("/var/www/html/output.txt", "w");
fwrite($fp, "Line 1\n");
fwrite($fp, "Line 2\n");
fclose($fp);
// Append to a log file.
$fp = fopen("/var/www/html/app.log", "a");
fwrite($fp, date("Y-m-d H:i:s") . " Process completed.\n");
fclose($fp);
// Practical example: process a CSV file line by line.
$fp = fopen("/var/www/html/users.csv", "r");
while (($line = fgets($fp)) !== false) {
$columns = explode(",", trim($line));
echo $columns[0] . ": " . $columns[1] . "\n"; // Split and print each line.
}
fclose($fp);
// Practical example: read a large file in chunks.
$fp = fopen("/var/www/html/large_file.dat", "r");
$chunk_size = 8192; // Read 8 KB at a time.
while (!feof($fp)) {
$chunk = fread($fp, $chunk_size);
// Process each chunk here.
}
fclose($fp);
Notes
Unlike file_get_contents(), which loads an entire file into memory at once, stream-based operations with fopen() let you read or write only as much data as you need at a time. When dealing with very large files, file_get_contents() can exhaust available memory because it loads the entire file at once. In such cases, using fopen() with fgets() to process one line at a time is the appropriate approach.
The write mode "w" truncates the file before writing, so any existing data will be lost. Use mode "a" if you want to append to an existing file. Always close a file with fclose() when you are done. Forgetting to close it can cause resource leaks.
For reading CSV files, PHP also provides the dedicated fgetcsv() function. Regarding file operation security, if you use user-supplied input as a file path, validate it with basename() or realpath() to prevent directory traversal attacks.
If you find any errors or copyright issues, please contact us.