PHP fgets() Function: Description, Parameters, Return Values, and Practical Examples
This article explains the PHP fgets() function, detailing its syntax, the required handle and optional length parameters, the possible return values, and provides three complete code examples that demonstrate reading lines from a file with proper error handling.
The fgets() function in PHP reads a single line from an open file pointer and returns it as a string.
Syntax: string fgets(resource $handle [, int $length])
Parameters: • $handle – a valid file pointer obtained from fopen() or fsockopen() that has not been closed. • $length (optional) – the maximum number of bytes to read (default 1024). The function stops at a newline, EOF, or after $length‑1 bytes.
Return value: The read line as a string (including the newline character) or FALSE on error or when the end of file is reached.
Example 1 – Read a file line by line with error handling: <?php $handle = @fopen("/tmp/inputfile.txt", "r"); if ($handle) { while (($buffer = fgets($handle, 4096)) !== false) { echo $buffer; } if (!feof($handle)) { echo "Error: unexpected fgets() fail\n"; } fclose($handle); } ?>
Example 2 – Read a single line from a file: <?php $file = fopen("test.txt", "r"); echo fgets($file); fclose($file); ?>
Example 3 – Read all lines from a file and output them with line breaks: <?php $file = fopen("test.txt", "r"); while (!feof($file)) { echo fgets($file) . " "; } fclose($file); ?>
Laravel Tech Community
Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.