The fread() reads from an open file.
PHP fread() Function has the following syntax.
fread(file,length)
Parameter | Is Required | Description |
---|---|---|
file | Required. | Open file to read from |
length | Required. | Maximum number of bytes to read |
This function returns the read string, or FALSE on failure.
<?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); ?>
Read 10 bytes from file:
<?php $file = fopen("test.txt","r"); fread($file,"10"); fclose($file); ?>
Read entire file:
<?php $file = fopen("test.txt","r"); fread($file,filesize("test.txt")); fclose($file); ?>