PHP fread() Function
Definition
The fread() reads from an open file.
Syntax
PHP fread() Function has the following syntax.
fread(file,length)
Parameter
Parameter | Is Required | Description |
---|---|---|
file | Required. | Open file to read from |
length | Required. | 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);
?>