PHP Function Reference

PHP fread() Function



The PHP fread() function reads from an open file. The function reads up to the specified length bytes from the file pointer referenced by stream. It stops reading if EOF (end of file) is reached or length bytes have been read, whichever comes first.

Note: It is a binary-safe file read.

Syntax

fread(stream, length)

Parameters

stream Required. Specify the file pointer to read from. It is typically created using fopen() function.
length Required. Specify the maximum number of bytes to read.

Return Value

Returns the read string or false on failure.

Example: fread() example

Lets assume that we have a file called test.txt. This file contains following content:

This is a test file.
It contains dummy content.

In the example below, the fread() function is used to read the content of this file.

<?php
//open the file in read mode
$fp = fopen("test.txt", "r");

//reading content of the file
$content = fread($fp, filesize("test.txt"));

//displaying the read content
echo $content;

//close the file
fclose($fp);
?>

The output of the above code will be:

This is a test file.
It contains dummy content.

Example: reading specified bytes from the file

Consider the example below where 20 bytes of data is read from the file. After that, the function stops reading.

<?php
//open the file in read mode
$fp = fopen("test.txt", "r");

//reading content of the file
$content = fread($fp, 20);

//displaying the read content
echo $content;

//close the file
fclose($fp);
?>

The output of the above code will be:

This is a test file.

Example: binary fread() example

On systems which differentiate between binary and text files (i.e. Windows), the file must be opened with 'b' included in fopen() mode parameter. See the example below:

<?php
//open the file in binary read mode
$fp = fopen("logo.gif", "rb");

//reading content of the file
$content = fread($fp, filesize("logo.gif"));

//close the file
fclose($fp);
?>

❮ PHP Filesystem Reference