W3docs

feof()

The feof() function in PHP is used to check whether the end of a file has been reached. It's a crucial function for server administrators and web developers who

Introduction to PHP feof() Function

The feof() function in PHP checks whether the end of a file has been reached. It is commonly used by developers and system administrators when reading or manipulating files.

The feof() function accepts one parameter: the file pointer you want to check. In this article, we'll discuss the syntax and parameters of the feof() function, along with examples of how to use it.

Syntax

The syntax of the feof() function is as follows:

The PHP syntax of feof()

bool feof ( $stream )
  • stream: the file pointer to check
  • Returns: booltrue if the file pointer is at the end of the file, false otherwise.

Parameters

The feof() function takes one required parameter:

  1. $stream: The file pointer you want to check. This parameter should be a resource created using the fopen() function or a similar function.

Important: feof() only returns true after a read function (such as fgets() or fread()) has attempted to read past the end of the file. Checking it immediately after opening a file will always return false. Additionally, feof() may not work reliably on non-seekable streams (like network sockets or pipes). Files ending with a newline character may also cause feof() to trigger right after the final line is read, so always verify the read function's return value.

Examples

Here are some examples of how to use the feof() function:

Example 1: Check if the end of a file has been reached after a read

The following example reads the first line of the file, then checks if the end has been reached:

Check if the end of a file has been reached in PHP

<?php

$fileHandle = fopen("example.txt", "r");
// Read the first line
$firstLine = fgets($fileHandle);

// Now check if we've reached the end
if (feof($fileHandle)) {
  echo "End of file reached";
} else {
  echo "End of file not reached";
}
fclose($fileHandle);
?>

Example 2: Standard loop pattern

The following example uses a safe while loop to read a file line by line until the end is reached. It also includes basic error handling for fopen():

Standard feof() loop in PHP

<?php

$fileHandle = fopen("example.txt", "r");
if ($fileHandle === false) {
  die("Error: Could not open file.");
}

while (($line = fgets($fileHandle)) !== false) {
  echo $line . "<br>";
}
fclose($fileHandle);
?>

This code will print each line of the file until the end of the file is reached.

Conclusion

The feof() function is essential for safely reading files in PHP. By understanding its behavior and using the examples above, you can integrate it into your file-handling logic effectively. For further questions, feel free to contact us.

Practice

Practice

What is the main purpose of the 'feof()' function in PHP?