Encodera

Thanks for reading!

Donate to the site — we work hard for you.

PHP reference

fread

Reads a number of bytes from an open file.

Syntax

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

Parameters

ParameterTypeDescription
$streamresourceAn open file.
$lengthintHow many bytes to read.

Return value

string|falseThe data read, or `false`.

Examples

The first bytes of a file:

<?php
 
$file = sys_get_temp_dir() . '/ref-fread.txt';
file_put_contents($file, 'Hello, world!');
 
$handle = fopen($file, 'r');
 
echo fread($handle, 5), '|', fread($handle, 100);
 
fclose($handle);

Output:

Hello|, world!

Notes

Each call continues where the previous one stopped. To read a whole file use file_get_contents().

See also

  • fopen — Opens a file for reading or writing piece by piece.
  • fgets — Reads one line from an open file.
  • file_get_contents — Reads a whole file into a string.

In the tutorial

  • Reading and writing files — Working with files in PHP — writing, reading, appending, reading line by line, checking existence and deleting.

Thanks for reading!

Donate to the site — we work hard for you.