The fread() function reads from an open file. The fread() function halts at the end of the file or when it reaches the specified length whichever comes first. It returns the read string on success. On failure, it returns FALSE.
Syntax
fread(file_pointer, length)
Parameters
file_pointer − A file system pointer resource created using fopen(). Required.
length − The maximum number of bytes to read. Required.
Return
The fread() function returns the read string on success. On failure, it returns FALSE.
Let’s say we have a file “one.txt” with the following line.
Cricket and Football are popular sports.
The following is an example that reads 7 bytes from a file.
Example
<?php $file_pointer = fopen("one.txt", "r"); // fread() function echo fread($file_pointer, "7"); fclose($file_pointer); ?>
Output
Cricket
Let us see another example that reads all the bytes from the same file “one.txt”.
Example
<?php $file_pointer = fopen("one.txt", "r"); // fread() function echo fread($file_pointer, filesize("one.txt")); fclose($file_pointer); ?>
Output
Cricket and Football are popular sports.