Using PHP feof() Function to Detect End-of-File

This article explains the PHP feof() function, its syntax, parameters, typical usage flow, provides a complete code example for reading a file line‑by‑line until EOF, and discusses important considerations and alternative methods for end‑of‑file detection.

php Courses
php Courses
php Courses
Using PHP feof() Function to Detect End-of-File

Function Syntax:

feof(file)

Parameter Description:

file

: required, the file pointer to check.

Basic Process of Using feof()

Open the file and obtain a file pointer.

Use feof() to check if the pointer has reached EOF.

If not at EOF, perform the desired operations.

If at EOF, close the file.

Usage Example

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

if ($file) {
    while (!feof($file)) {
        $line = fgets($file);
        echo $line;
    }
    fclose($file);
}

In this example we open "data.txt", loop with while and feof() to read each line until EOF, then close the file. feof() returns a boolean: true when the pointer is at EOF, false otherwise. Note that feof() only checks the pointer position; it does not verify file existence or readability, so the file must be successfully opened first.

feof() does not move the file pointer; to move it you can use functions like fseek() or rewind().

Alternative methods to detect end-of-file include checking if the read line is empty or if the number of bytes read is zero, depending on requirements.

Summary

The PHP feof() function detects whether a file pointer has reached the end of a file, helping prevent reading invalid data. Ensure the file is opened successfully before using feof(), and consider other functions like fseek() or alternative EOF detection methods as needed.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

file-handlingfeofend-of-file
php Courses
Written by

php Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.