Skip to content
PHP Logo

What are best practices for checking for EOF (end of file) when using fgets in PHP scripts?

When using fgets in PHP scripts to read lines from a file, it is important to check for the end of file (EOF) to avoid reading past the end of the file and causing errors. One common way to check for EOF is to use a while loop that continues reading lines until fgets returns false, indicating the end of the file has been reached.

php
$handle = fopen("file.txt", "r");

if ($handle) {
    while (($line = fgets($handle)) !== false) {
        // Process the line here
    }

    fclose($handle);
}