The fread Function
The fread
function reads data from an open file. The first parameter is a file pointer (resource) obtained via fopen
, and the second is the maximum number of bytes to read. The function returns the read data or false
on error.
Syntax
fread(resource $handle, int $length): string|false
Example
Read the first 10
bytes from a file:
<?php
$file = fopen('data.txt', 'r');
$res = fread($file, 10);
fclose($file);
echo $res;
?>
Code execution result:
'Some text '
Example
Read the entire file:
<?php
$file = fopen('data.txt', 'r');
$res = fread($file, filesize('data.txt'));
fclose($file);
echo $res;
?>
Code execution result:
'Complete file content'
Example
Read a file in parts:
<?php
$file = fopen('data.txt', 'r');
while (!feof($file)) {
echo fread($file, 5) . "\n";
}
fclose($file);
?>
Code execution result:
'First'
' part'
' of t'
'ext'
See Also
-
the
fwrite
function,
which writes to a file -
the
fgets
function,
which reads a line from a file -
the
file_get_contents
function,
which reads an entire file