Current Location: Home> Latest Articles> PHP feof() Function Explained: How to Check If the File Pointer Reached the End of the File

PHP feof() Function Explained: How to Check If the File Pointer Reached the End of the File

M66 2025-06-18

PHP feof() Function Explained: How to Check If the File Pointer Reached the End of the File

PHP, as a powerful scripting language for web development, offers a rich set of functions to handle various tasks. File handling is a common use case in PHP, and the feof() function is especially important. feof() is used to check if the file pointer has reached the end of the file. In this article, we will explain the usage of the feof() function and provide code examples to help developers handle files efficiently.

Overview of the feof() Function

feof() is one of the built-in file handling functions in PHP. It is used to check if the file pointer has reached the end of the file during file operations. The syntax of the function is as follows:

bool feof ( resource $handle )

Function Parameters and Return Value

  • handle: The file pointer resource, typically returned by the fopen() function when a file is opened.
  • Return value: Returns true if the file pointer has reached the end of the file, otherwise it returns false.

feof() Function Code Example

To help understand the actual use of the feof() function, here’s a code example. Suppose we have a text file named "example.txt" with the following content:

Hello World!

This is an example file.

Below is the PHP code that reads this file and checks if the file pointer has reached the end of the file:

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

if ($handle) {

// Read the file line by line

while (($line = fgets($handle)) !== false) {

// Output each line's content

echo $line;

}

// Check if the file pointer has reached the end of the file

if (feof($handle)) {

echo "File pointer has reached the end of the file.";

} else {

echo "File pointer has not reached the end of the file.";

}

// Close the file pointer

fclose($handle);

}

Execution Result

After running the above code, the following result will be displayed:

Hello World!

This is an example file.

File pointer has reached the end of the file.

The result indicates that the file content was successfully read and that the file pointer correctly detected that it had reached the end of the file.

Conclusion

The feof() function is extremely useful in PHP file handling. It helps developers check whether the file pointer has reached the end of the file, preventing redundant read operations. When using feof(), developers should ensure that they open the file using fopen() first and close the file pointer with fclose() after processing, to properly manage resources.

This article explained the basic usage of the feof() function and provided a practical code example. We hope this helps readers better understand and apply the function in their projects.