PHP fread() Function
In this chapter you will learn:
- Definition for PHP fread() Function
- Syntax for PHP fread() Function
- Parameter for PHP fread() Function
- Return for PHP fread() Function
- Example - reads from a file
- Example - Read 10 bytes from file
- Example - Read entire file
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/*from ja v a 2 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//j a va 2 s.co m
$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/*j a v a 2s . c o m*/
$file = fopen("test.txt","r");
fread($file,"10");
fclose($file);
?>
Example 3
Read entire file:
<?php//from j a va 2 s . co m
$file = fopen("test.txt","r");
fread($file,filesize("test.txt"));
fclose($file);
?>
Next chapter...
What you will learn in the next chapter:
- Definition for PHP fscanf() Function
- Syntax for PHP fscanf() Function
- Parameter for PHP fscanf() Function
- Additional format
- Return for PHP fscanf() Function
- Example - parses the input from an open file according to the specified format
Home » PHP Tutorial » PHP File Functions