Visit the Official PHP Website

Search this Site

PHP Programming

By James N Hitz

Reading From Files With fread()

Reading file contents is done using the fread() function as follows:

  $fileContents = fread("file_to_read", bytes_to_read);

The first argument - "file_to_read" is a file handle pointing to a previously opened file (of course you can't read a closed file).

PS: "file_to_read" is a file pointer (filehandle) and NOT a file name!!

The second argument (bytes_to_read) specifies how much content you want to read from a file. If you want to read the entire file and you don't know how big it is, use PHP's filesize():

$filesize = filesize(filename)

Here the filesize() function expects you to specify the filename AND NOT the filehandle (file pointer). This will need a little getting used to.

Lets take an example.

The following example opens a file, reads the contents and prints them out, before finally closing the file:

<HTML><HEAD><TITLE>using data files with PHP</TITLE></HEAD>
<BODY bgcolor="black" text="white">
<?php
 $file2access="/www/home/list.txt"; //our data file.
 if(!$filehandle = fopen($file2access,'r')){
    print "Error. Could not open $file2access in read only mode";
 }else {
   /* file opened ok. Read contents but first get file size */

   $contents = fread($filehandle,$filesize);
   print "The contents of <B>$file2access</B>are:<BR>".
         "<BLOCKQUOTE><B>$contents</B></BLOCKUOTE>";

   //close file
   if(!fclose ($filehandle)){
	print "<P>Error.  Cannot close file <b>$file2access</b>";
   }
 }
?>
<BODY></HTML>

<< Assumptions | Writing to Files >>

JamHitz Productions