PHP File Open Read

The fopen() function opens a file and returns a handle you can pass to reading functions like fread() and fgets() to pull data out one piece at a time.

Opening a file with fopen()

To read a file with the low-level functions, you first open it with fopen(). This function takes the file name and a mode that tells PHP what you intend to do. For reading, the mode is 'r', which opens the file at the beginning and does not allow writing. fopen() returns a file handle, a special value that every later function uses to refer to this open file.

ModeMeaning
rRead only, pointer at start of file
r+Read and write, pointer at start
wWrite only, truncates file to zero length
aWrite only, appends to end of file
xCreate and write, fails if file already exists

Reading an entire file with fread()

<?php
$handle = fopen("report.txt", "r");

if ($handle) {
    // Read the whole file using its size in bytes
    $data = fread($handle, filesize("report.txt"));
    echo $data;
    fclose($handle);
}
?>

Reading line by line

For large files it is better to read one line at a time so you never load the whole file into memory. fgets() returns the next line each time it is called, and feof() tells you when the end of the file has been reached. Combining them in a while loop is a common pattern.

Looping through a file line by line

<?php
$handle = fopen("report.txt", "r");

if ($handle) {
    while (!feof($handle)) {
        $line = fgets($handle);
        echo $line . "<br>";
    }
    fclose($handle);
}
?>
Note: If you only need the whole file as a string, file_get_contents() is simpler than fopen plus fread. Reach for fopen when you want to read incrementally or keep the file open for repeated operations.

Reading a file into an array

The file() function is a handy shortcut that reads an entire file and returns it as an array, with one element per line. This is convenient when you want to process or count lines without managing a handle yourself.

Using file() to get an array of lines

<?php
$lines = file("report.txt", FILE_IGNORE_NEW_LINES);

echo "This file has " . count($lines) . " lines.\n";

foreach ($lines as $number => $text) {
    echo ($number + 1) . ": " . $text . "\n";
}
?>
  • fopen() returns false if the file cannot be opened, so always check the handle before using it.
  • fclose() should be called once you finish, especially inside loops or long-running scripts.
  • fgets() reads up to a newline or the given length; feof() detects the end of the file.
  • file() and file_get_contents() are simpler when you do not need incremental control.