How to Reads from the current position in a file - until EOF, and writes the result to the output buffer in PHP ?


In PHP, we can read from the current position in a file until EOF and write the result to the output buffer using the following methods:

Method 1: Using fread() and fwrite() functions

<?php
$filename = "example.txt";
$handle = fopen($filename, "r");
if ($handle) {
    while (!feof($handle)) {
        $buffer = fread($handle, 1024);
        fwrite(STDOUT, $buffer);
    }
    fclose($handle);
}
?>

In the above code, we have used the fread() function to read the file content from the current position until EOF and store it in a buffer. Then we have used the fwrite() function to write the buffer content to the output buffer.

Method 2: Using file_get_contents() function

<?php
$filename = "example.txt";
$content = file_get_contents($filename, NULL, NULL, ftell($handle));
echo $content;
?>

In the above code, we have used the file_get_contents() function to read the file content from the current position until EOF and store it in a variable. Then we have used the echo statement to write the variable content to the output buffer.

Note: In both methods, we have used the ftell() function to get the current position in the file.



About the author

William Pham is the Admin and primary author of Howto-Code.com. With over 10 years of experience in programming. William Pham is fluent in several programming languages, including Python, PHP, JavaScript, Java, C++.