PHP fread() function

Definition and Usage

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

Syntax

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

Description

fread() from the file pointer file Read at most length 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.

Tips and Comments

Tip:If you just want to read the contents of a file into a string, use file_get_contents()has much better performance 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);
?>