Mastering PHP’s feof(): Detect End‑of‑File Efficiently

This guide explains PHP’s feof() function, its syntax, parameters, step‑by‑step usage, example code, important considerations, and alternative methods for detecting when a file pointer reaches the end, helping developers handle file operations safely and efficiently.

php Courses
php Courses
php Courses
Mastering PHP’s feof(): Detect End‑of‑File Efficiently

PHP function feof() is used to check whether a file pointer has reached the end of a file. When processing files, you often need to read line by line or according to certain rules, and feof() helps determine if the file has been completely read, preventing invalid data.

Function syntax:

feof(file)

Parameter description:

file

: required. Specifies the file pointer to be checked.

Basic usage flow:

Open the file and obtain a file pointer.

Use feof() to test whether the pointer is at the end.

If not at the end, perform the desired operations.

If at the end, close the file.

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, use feof() inside a while loop to check the pointer, read each line with fgets(), output it, and close the file when done. feof() returns a boolean: true if the pointer is at the end, false otherwise. Note that feof() only checks the pointer position; it does not verify file existence or readability. Ensure the file is successfully opened before calling feof().

Also, feof() does not move the pointer. To move it, use functions such as 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.

Summary

The PHP feof() function detects whether a file pointer has reached the end of a file, helping avoid reading invalid data. Use it after confirming the file is opened and the pointer is valid; other functions like fseek() or rewind() can move the pointer, and alternative checks may be employed.

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.

BackendPHPfile-handlingfeofphp-tutorialfile-pointer
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.