HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

PHP File Open / Read

Reading files is a fundamental part of server-side programming. While readfile() is good for simple output, fopen() provides much more control over how you interact with the file system.


1. The fopen() Function

To open a file, use fopen(). You must specify the filename and the mode (how you want to open it).

Mode Description
rRead only. Pointer starts at the beginning.
r+Read/Write. Pointer starts at the beginning.
wWrite only. Overwrites existing content.
aAppend. Pointer starts at the end.
<?php
    $myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
?>

2. Reading with fread()

The fread() function reads from an open file. It takes two parameters: the file handle and the maximum number of bytes to read.

<?php
    echo fread($myfile, filesize("webdictionary.txt"));
?>

3. Closing with fclose()

Always close your files using fclose() to free up server resources.

<?php
    fclose($myfile);
?>

4. Reading One Line - fgets()

For large files, it is better to read line by line using a loop and the feof() (End Of File) check.

<?php
    $myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
    // Output one line until end-of-file
    while(!feof($myfile)) {
        echo fgets($myfile) . "<br>";
    }
    fclose($myfile);
?>
Pointer Logic: Every time you read a character or a line, PHP moves an internal "pointer" forward. If you read the entire file once, you must close and re-open it to read from the start again.
Pro Tip: Use fgetc() if you need to read a file character by character, which is useful for custom parsing logic.

Key Takeaways

  • fopen() opens a connection to a file.
  • Modes like r, w, and a define the access type.
  • fread() reads a specific number of bytes.
  • fgets() reads until it hits a newline character.
  • fclose() is mandatory for good resource management.