PHP fread( ) Function
Last Updated :
31 Mar, 2023
The fread() function in PHP is an inbuilt function that reads up to length bytes from the file pointer referenced by file from an open file. The fread() function stops at the end of the file or when it reaches the specified length passed as a parameter, whichever comes first. The file and the length which has to be read are sent as parameters to the fread() function and it returns the read string on success, or FALSE on failure.
Syntax:
string fread ( $file, $length )
Parameters Used:
The fread() function in PHP accepts two parameters.
- $file: It is a mandatory parameter which specifies the file.
- $length: It is a mandatory parameter that specifies the maximum number of bytes to be read.
Return Value: It returns the read string on success, or False on failure.
Exceptions:
- Both binary data, like images and character data, can be written with this function since fread() is binary-safe.
- To get the contents of a file only into a string, use file_get_contents() as it has much better performance than the code above.
- Since systems running Windows differentiate between binary and text files, the file must be opened with ‘b’ included in fopen() mode parameter.
Below programs illustrate the fread() function:
Suppose a file named gfg.txt contains the following content:
Geeksforgeeks is a portal of geeks!
Program 1:
<?php
$myfile = fopen ( "gfg.txt" , "r" );
echo fread ( $myfile , "13" );
fclose( $myfile );
?>
|
Output:
Geeksforgeeks
Program 2:
<?php
$myfile = fopen ( "gfg.txt" , "r" );
echo fread ( $myfile , filesize ( "gfg.txt" ));
fclose( $myfile );
?>
|
Output:
Geeksforgeeks is a portal of geeks!
Program 3:
<?php
$myfile = "logo.jpg" ;
$myhandle = fopen ( $myfile , "rb" );
echo fread ( $myhandle , filesize ( $myfile ));
fclose( $myhandle );
?>
|
Output:
256
Reference:
http://php.net/manual/en/function.fread.php
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...