|
| HOW TO READ FILES USING THE fread() FUNCTION IN PHP
The fread() function is used to read from a file that is opened. It takes as parameters, the resource file handle and the length in bytes of the file. It reads from this file to the specified length or till the end of file, whichever comes first.
The general format is:
fread(filehandle, length in bytes);
Example:
<?
$myFile="test.txt";
$fd=fopen($myFile, "r");
$contents=fread($fd, "100");
fclose($fd);
?>
First, we use the fopen function to open the file in read or write mode. Then we use the fread function to read file to 100 bytes. We then close the file using the fclose function. $contents variable then holds the contents of the file. If you echo $contents, you will see the contents of the file outputted to your screen.
If you want to read the entire file but do not know the entire size of the file in bytes, then use the handy filesize() function in the fread() function as follows:
<?
$myFile="test.txt";
$fd=fopen($myFile, "r");
$contents=fread($fd, filesize($myFile));
fclose($fd);
?>
 |
|
|