PHP fread() Function
Quick summary: The PHP fread() function reads a specified number of bytes from an open file pointer.
PHP fread() Syntax
fread(resource $stream, int $length): string|false
PHP
PHP fread() Basic examples
$h = fopen('test.txt', 'r');
$data = fread($h, 5);
fclose($h);
var_dump($data);
PHP
Output:
string(5) "Hello"
Reads the first 5 bytes from a file.
PHP fread() Real-world usage
$h = fopen('large.log', 'r');
$chunk = fread($h, 1024);
fclose($h);
PHP
Output:
string(1024) "..."
Reads large files in chunks to save memory.
PHP fread() Edge cases
$h = fopen('test.txt', 'r');
var_dump(fread($h, 0));
fclose($h);
PHP
Output:
string(0) ""
Reading 0 bytes returns an empty string.
PHP fread() Common mistakes
Reading without checking file size
fread may return fewer bytes than requested.
Incorrect
fread($h, 1024);
Correct
while (!feof($h)) { fread($h, 1024); }
Use feof() when reading streams.
PHP fread() Frequently Asked Questions
What does fread() do?
Reads data from an open file pointer.
Syntax?
fread(resource, length).
Use case?
Reading large files in chunks.
Does it modify file?
No.
Requires fopen()?
Yes.
Performance?
Efficient for large files.
Handles binary?
Yes.
Common mistake?
Wrong length.
Can return false?
Yes.
EOF handling?
Check feof().
Alternative?
file_get_contents().
Safe?
Yes.