What is fread in PHP?

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.

Syntax

The syntax for fread function is shown below:

fread(resource $stream, int $length): string|false

Parameters

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 lengthnumber of bytes, whichever comes first.
  • length: This is also a required parameter. This parameter specifies the number of bytes to be read from the file.

Return value

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.

Code

The following code shows how we can use the fread function.

main.php
test.txt
<?php
$file = fopen("test.txt","r"); // open the file
while(!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

Copyright ©2025 Educative, Inc. All rights reserved