Using PHP fgets() to Read Files Line by Line

PHP's fgets() function reads a line from an opened file or stream, optionally limiting the number of bytes, and can be used for text and binary files; the article explains its syntax, examples for line-by-line reading, length control, binary handling, and error checking.

php Courses
php Courses
php Courses
Using PHP fgets() to Read Files Line by Line

PHP fgets() Function Overview

fgets() reads a line from an opened file resource or a filename, optionally limiting the maximum number of bytes per read. fgets(file,length) The file parameter is a file handle, and length is optional; if omitted, PHP reads until a newline or EOF.

1. Reading a line from a file

Typical usage opens a file with fopen(), then loops until feof() while calling fgets() to retrieve each line.

$file = fopen("data.txt", "r");
while (!feof($file)) {
    $line = fgets($file);
    echo $line;
}
fclose($file);

2. Specifying maximum bytes per read

Providing the optional length argument limits the number of bytes returned; for example, setting it to 1024 reads up to 1024 bytes per call.

$file = fopen("data.txt", "r");
while (!feof($file)) {
    $line = fgets($file, 1024);
    echo $line;
}
fclose($file);

3. Reading binary files

When reading binary data, open the file in binary mode (e.g., "rb") and use fgets() to obtain each line, remembering that binary streams may contain newline characters.

$file = fopen("image.jpg", "rb");
while (!feof($file)) {
    $data = fgets($file);
    // process $data
}
fclose($file);

4. Error handling

Check the result of fopen() before reading; if the file cannot be opened, fgets() will not be called and an error message can be displayed.

$file = fopen("data.txt", "r");
if ($file) {
    while (!feof($file)) {
        $line = fgets($file);
        // process $line
    }
    fclose($file);
} else {
    echo "Failed to open file";
}

Summary

The fgets() function is a versatile tool for reading text or binary files line by line in PHP, offering optional byte limits and straightforward error handling, which helps improve file‑processing efficiency and reliability.

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.

TutorialfgetsFile Reading
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.