fpassthru()
What is the fpassthru() Function?
The fpassthru() function is a built-in PHP function that reads the contents of a file from the current file pointer position to the end of the file and writes them directly to the standard output stream. This function is used to read large files without loading them into memory.
It returns the number of bytes written from the given file pointer to the output on success, or false on failure.
Here's the basic syntax of the fpassthru() function:
The PHP syntax of fpassthru()
fpassthru(file);Where file is the file pointer to read from.
How to Use the fpassthru() Function?
Using the fpassthru() function is straightforward. Here are the steps to follow:
- Open the file with
fopen()and ensure the file pointer is at the desired starting position. - Call
fpassthru()with the file pointer. It will read until EOF and write to the output stream. - Check the return value to confirm success, then close the file with
fclose().
Here's an example code snippet that demonstrates how to use the fpassthru() function:
How to Use the fpassthru() Function?
<?php
$filename = 'largefile.txt';
$file = fopen($filename, 'r');
if ($file) {
if (fpassthru($file) === false) {
echo "Error reading file!";
}
fclose($file);
} else {
echo "Unable to open file!";
}In this example, we open the file largefile.txt using the fopen() function in read-only mode. We check if the file was opened successfully using an if statement, and if it was, we output the contents of the file to the standard output stream using the fpassthru() function. We verify the return value to handle potential read errors before closing it using the fclose() function.
Note on output buffering: If PHP output buffering is active (e.g., via
ob_start()),fpassthru()will write directly into the current output buffer instead of sending data immediately to the browser.
Conclusion
The fpassthru() function is a useful tool in PHP for reading large files without loading them into memory. By following the steps outlined in this guide, you can easily use the fpassthru() function in your PHP projects to read the contents of files from the current pointer position and output them to the standard output stream.
Practice
What is the purpose of the fpassthru() function in PHP?