PHP fread() Function

Definition and Usage

The fread() function reads a file (can be safely used for binary files).

Syntax

fread(file,length)
Parameters Description
file Required. Specifies the file to read.
length Required. Specifies the maximum number of bytes to read.

Description

fread() from the file pointer file Read at most length number of bytes. This function stops reading the file after reading at most length number of bytes, or when EOF is reached, or (for network streams) when a packet is available, or (after opening a user space stream) when 8192 bytes have been read, depending on which condition is met first.

Returns the read string, or false if an error occurs.

Hints and Comments

Hint:If you just want to read the content of a file into a string, use file_get_contents()Its performance is much better than fread().

Instance

Example 1

Read 10 bytes from the file:

<?php
$file = fopen("test.txt","r");
fread($file,"10");
fclose($file);
?>

Example 2

Read the entire file:

<?php
$file = fopen("test.txt","r");
fread($file, filesize("test.txt"));
fclose($file);
?>