Skip to content

PHP Tutorial File Handling

Reading Files

Lesson 165 of 369 2 min read By Deepak Paswan Updated Oct 5, 2026

PHP has several ways to read a file. They differ in how much they read at a time.

The examples below use a small file. Create it first:

index.php
PHP
<?php
file_put_contents("fruits.txt", "apple\nbanana\ncherry\n");

echo filesize("fruits.txt") . " bytes";
Output
OUTPUT
20 bytes

fgets(): one line at a time

Best for large files, because only one line is in memory.

index.php
PHP
<?php
file_put_contents("fruits.txt", "apple\nbanana\ncherry\n");

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

while (($line = fgets($handle)) !== false) {
    echo "Line: " . trim($line) . "\n";
}

fclose($handle);
Output
OUTPUT
Line: apple
Line: banana
Line: cherry

fgets() returns false at the end of the file. Compare with !== false, so that a line containing "0" does not stop the loop.

feof(): are we at the end?

index.php
PHP
<?php
file_put_contents("fruits.txt", "apple\nbanana\n");

$handle = fopen("fruits.txt", "r");
$count = 0;

while (!feof($handle)) {
    $line = fgets($handle);
    if ($line !== false) {
        $count++;
    }
}

fclose($handle);
echo $count . " lines";
Output
OUTPUT
2 lines

file(): the whole file as an array of lines

index.php
PHP
<?php
file_put_contents("fruits.txt", "apple\nbanana\n\ncherry\n");

$lines = file("fruits.txt", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);

print_r($lines);
Output
OUTPUT
Array
(
    [0] => apple
    [1] => banana
    [2] => cherry
)

FILE_IGNORE_NEW_LINES removes the \n at the end of each item. FILE_SKIP_EMPTY_LINES drops blank lines. Use file() only for files that fit easily in memory.

fread(): a number of bytes

index.php
PHP
<?php
file_put_contents("fruits.txt", "apple\nbanana\n");

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

echo fread($handle, 5);

fclose($handle);
Output
OUTPUT
apple

To read a big file in pieces, call fread() in a loop with a size such as 8192.

readfile(): send a file to the output

index.php
PHP
<?php
file_put_contents("fruits.txt", "apple\nbanana\n");

$bytes = readfile("fruits.txt");

echo "($bytes bytes)";
Output
OUTPUT
apple
banana
(13 bytes)

readfile() prints the file and returns how many bytes it sent. It is the right tool to send a download without loading it all into memory.

Choosing

NeedUse
Whole small file as a stringfile_get_contents()
Whole small file as linesfile()
Big file, line by linefopen() + fgets()
Big file in chunksfopen() + fread()
Send a file to the browserreadfile()
lightbulb
Files can be big
A 2 GB log file does not fit in memory. Read big files one line at a time with fgets(), or use a generator (see Generators).