PHP Tutorial - PHP fread() Function






Definition

The fread() reads from an open file.

Syntax

PHP fread() Function has the following syntax.

fread(file,length)

Parameter

ParameterIs RequiredDescription
fileRequired.Open file to read from
lengthRequired.Maximum number of bytes to read

Return

This function returns the read string, or FALSE on failure.

Example 1

<?PHP
      $huge_file = fopen("VERY_BIG_FILE.txt", "r");
      while (!feof($huge_file)) {
              print fread($huge_file, 1024);
      }
      fclose($huge_file);
?>

feof() takes a file handle and returns true if you are at the end of the file or false otherwise.

fread() is good for reading a small part of the file. For example, Zip files start with the letters "PK", so we can do a quick check to ensure a given file is a Zip file with this code:

<?PHP
      $zipfile = fopen("data.zip", "r");
      if (fread($zipfile, 2) != "PK") {
        print "Data.zip is not a valid Zip file!";

      }
      fclose($zipfile);
?>




Example 2

Read 10 bytes from file:

<?php
$file = fopen("test.txt","r");
fread($file,"10");
fclose($file);
?>

Example 3

Read entire file:

<?php
$file = fopen("test.txt","r");
fread($file,filesize("test.txt"));
fclose($file);
?>