PHP offers many functions for file manipulation. The fread
function in PHP reads the content from an already open file. It is a binary-safe read option that allows binary data in addition to normal text content to be read.
The syntax for fread
function is shown below:
fread(resource $stream, int $length): string|false
The fread
function has two parameters:
file
: This is a required parameter. This is the pointer of the file stream that points to a file that is already open. The fread
function stops reading from the file at the end of the file or when it reaches the specified length
: This is also a required parameter. This parameter specifies the number of bytes to be read from the file.The fread()
function returns the read content from the file in the form of a string.
If it is unable to return the content due to an error or by coming to the end of the file, it returns false
.
The following code shows how we can use the fread
function.
<?php$file = fopen("test.txt","r"); // open the filewhile(!feof($file)) //checks if at end of the file{echo fread($file, 32); //reads the content of 32 bytes from the file}fclose($file); // close the file?>
Free Resources