Reading Files in PHP

Our first program will demonstrate reading files in PHP. Here’s the full source code with explanations:

<?php

// Reading and writing files are basic tasks needed for
// many PHP programs. First we'll look at some examples of
// reading files.

// This helper will streamline our error checks below.
function check($result) {
    if ($result === false) {
        throw new Exception("Error occurred");
    }
}

// Perhaps the most basic file reading task is
// slurping a file's entire contents into memory.
$dat = file_get_contents("/tmp/dat");
check($dat);
echo $dat;

// You'll often want more control over how and what
// parts of a file are read. For these tasks, start
// by opening a file to obtain a file handle.
$f = fopen("/tmp/dat", "r");
check($f);

// Read some bytes from the beginning of the file.
// Allow up to 5 to be read but also note how many
// actually were read.
$b1 = fread($f, 5);
check($b1);
$n1 = strlen($b1);
printf("%d bytes: %s\n", $n1, $b1);

// You can also seek to a known location in the file
// and read from there.
check(fseek($f, 6, SEEK_SET));
$b2 = fread($f, 2);
check($b2);
$n2 = strlen($b2);
$o2 = ftell($f) - $n2;
printf("%d bytes @ %d: ", $n2, $o2);
printf("%s\n", $b2);

// The fseek function allows seeking relative to the
// current position or the end of the file as well.
check(fseek($f, 4, SEEK_CUR));
check(fseek($f, -10, SEEK_END));

// The SplFileObject provides an object-oriented interface
// for file operations and includes methods that may be
// helpful for file reading.
$f = new SplFileObject("/tmp/dat", "r");
check($f);
$f->fseek(6);
$b3 = $f->fread(2);
check($b3);
$n3 = strlen($b3);
$o3 = $f->ftell() - $n3;
printf("%d bytes @ %d: %s\n", $n3, $o3, $b3);

// There is no built-in rewind, but
// fseek(0, SEEK_SET) accomplishes this.
$f->fseek(0);

// The SplFileObject also implements methods from Iterator,
// making it easy to read a file line by line.
$f->rewind();
$b4 = $f->fgets();
check($b4);
printf("5 bytes: %s", substr($b4, 0, 5));

// Close the file when you're done.
$f = null;

To run this program and see its output:

$ echo "hello" > /tmp/dat
$ echo "php" >>   /tmp/dat
$ php reading-files.php
hello
php
5 bytes: hello
2 bytes @ 6: ph
2 bytes @ 6: ph
5 bytes: hello

This example demonstrates various methods of reading files in PHP, including reading entire files, reading specific bytes, seeking to different positions in a file, and using the SplFileObject for more advanced file operations.

Next, we’ll look at writing files.