How to Use fgets in PHP: Read Lines from a File Easily
In PHP,
fgets reads a single line from an open file pointer until it reaches a newline or the specified length. You first open a file with fopen, then use fgets inside a loop to read each line until the end of the file.Syntax
The fgets function reads a line from a file pointer. It takes two parameters:
resource $handle: The file pointer returned byfopen.int $length(optional): Maximum number of bytes to read. If omitted, it reads up to the end of the line or up to 1024 bytes by default.
The function returns the line as a string or false on end of file or error.
php
string|false fgets(resource $handle, int $length = 1024);
Example
This example opens a text file named example.txt and reads it line by line using fgets. It prints each line until the file ends.
php
<?php $filename = 'example.txt'; $handle = fopen($filename, 'r'); if ($handle) { while (($line = fgets($handle)) !== false) { echo $line; } fclose($handle); } else { echo "Failed to open file."; } ?>
Output
Hello, this is line one.
This is line two.
And this is line three.
Common Pitfalls
- Not checking if
fopensucceeded before usingfgetscauses errors. - Using
fgetswithout a loop reads only one line. - For binary files or very long lines, specifying
$lengthis important to avoid memory issues. - Remember to close the file with
fcloseto free resources.
php
<?php // Wrong: Not checking fopen $handle = fopen('file.txt', 'r'); $line = fgets($handle); // May cause error if fopen failed // Right: Check fopen $handle = fopen('file.txt', 'r'); if ($handle) { $line = fgets($handle); fclose($handle); } ?>
Quick Reference
| Function | Description |
|---|---|
| fopen($filename, 'r') | Open file for reading |
| fgets($handle, $length) | Read one line from file |
| feof($handle) | Check if end of file reached |
| fclose($handle) | Close the open file |
Key Takeaways
Always open a file with fopen before using fgets to read lines.
Use fgets inside a loop to read the entire file line by line.
Check if fopen succeeded to avoid errors when reading.
Close the file with fclose after finishing reading.
Specify length in fgets to control memory for very long lines.