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

This article explains PHP’s built‑in feof() function, detailing its syntax, parameters, return values, and provides a complete code example that reads a file line‑by‑line, checks for end‑of‑file, and demonstrates proper use of fopen(), fgets(), feof() and fclose() to manage resources.

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

PHP is a widely used scripting language for web development, offering a rich set of functions to handle various tasks efficiently. The built‑in feof() function checks whether a file pointer has reached the end of a file.

Parameter description:

$handle

: the file pointer resource returned by fopen().

Return value explanation:

Returns true if the file pointer is at the end of the file; otherwise returns false.

Example function signature: bool feof ( resource $handle ) Assume a file example.txt containing:

Hello World!
This is an example file.

The following script reads the file line by line, checks for end‑of‑file, and outputs appropriate messages:

$handle = fopen("example.txt", "r");
if ($handle) {
    // Read file line by line
    while (($line = fgets($handle)) !== false) {
        echo $line;
    }
    // Check if pointer reached end of file
    if (feof($handle)) {
        echo "文件指针已到达文件末尾。";
    } else {
        echo "文件指针未到达文件末尾。";
    }
    // Close the file pointer
    fclose($handle);
}

Running this code outputs the file contents followed by the message indicating that the file pointer has reached the end of the file.

Summary:

The feof() function is a PHP file‑handling function that detects when the file pointer reaches the end of a file, helping developers avoid unnecessary reads. Use it after opening a file with fopen() and close the resource with fclose() when done.

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.

PHPTutorialfile-handlingfeof
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.