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/* w  ww.ja  v  a2  s  . c om*/
      $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/*from ww  w .  j  a v a  2  s.  c om*/
      $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// w  w  w . j  ava2  s.  c o  m
$file = fopen("test.txt","r");
fread($file,"10");
fclose($file);
?>

Example 3

Read entire file:


<?php/* w  ww .ja va2 s .com*/
$file = fopen("test.txt","r");
fread($file,filesize("test.txt"));
fclose($file);
?>




















Home »
  PHP Tutorial »
    Function reference »




PHP Array Functions
PHP Calendar Functions
PHP Class Functions
PHP Data Type Functions
PHP Date Functions
PHP File Functions
PHP Image Functions
PHP Math Functions
PHP MySQLi Functions
PHP SimpleXML Functions
PHP String Functions
PHP XML Functions
PHP Zip Functions