Reading Files

In order to read a file, the file must first be opened with the appropriate mode to allow you to perform the function(s) that you have planned.

Three different functions are useful for reading files.

Function Description
feof() Tests For End-of-File On a File Pointer
fgets() Gets Line From File Pointer
fread() Binary-Safe File Read
filesize() Gets the Size Of a Given File

The end-of-file test function, feof(), is commonly used along with the fgets() function to get (read) the entire contents of a file, one line at a time. The filesize() function is commonly used along with the fread() function to read an entire file, otherwise fread() requires that a length/limit be specified and will stop reading the file once that length (number of bytes) has been reached.

Let's look at some examples before we continue.

<?php
  $FileName = "test.txt";
  $FileHandle = fopen($FileName, 'r') or die("File Cannot Be Opened");
  $FileData = fread($FileHandle, filesize($FileName));
  fclose($FileHandle);

?>

The above example opens a file and stores the entire contents of the file in a variable before closing the file. The variable containing the file's contents can then be used as needed.

<?php
  $FileName = "test.txt";
  $FileHandle = fopen($FileName, 'r') or die("File Cannot Be Opened");
  while (!feof($FileHandle)) {
    echo fgets($FileHandle) . '<br>';
  }
  fclose($FileHandle);

?>

The above code opens a file and, while the file still contains unread data, reads each line and displays it before closing the file.

Next, we will learn how to write data to a file.

Summary:

Function Description
feof() Tests For End-of-File On a File Pointer
fgets() Gets Line From File Pointer
fread() Binary-Safe File Read
filesize() Gets the Size Of a Given File