Using PHP fread() to Read Files: Syntax, Parameters, Return Values, and Practical Examples

This article explains PHP's fread() function, detailing its syntax, parameters, return values, stopping conditions, and provides three practical code examples for reading regular files, binary files, and streaming data from a URL.

Laravel Tech Community
Laravel Tech Community
Laravel Tech Community
Using PHP fread() to Read Files: Syntax, Parameters, Return Values, and Practical Examples

The fread() function reads up to a specified number of bytes from an open file pointer in PHP and can safely handle binary files.

Syntax: string fread(resource $handle, int $length) Reading stops when either the requested $length bytes have been read or the end of the file (EOF) is reached.

Parameters :

handle – a file system pointer, typically obtained from fopen().

length – the maximum number of bytes to read.

Return value – the read string on success, or FALSE on failure.

Example 1 – Read a regular text file:

<?php
$filename = "/usr/local/something.txt";
$handle = fopen($filename, "r");
$contents = fread($handle, filesize($filename));
fclose($handle);
?>

Example 2 – Read a binary file (e.g., an image):

<?php
$filename = "c:\\files\\somepic.gif";
$handle = fopen($filename, "rb");
$contents = fread($handle, filesize($filename));
fclose($handle);
?>

Example 3 – Stream data from a URL using a loop:

<?php
$handle = fopen("http://www.example.com/", "rb");
$contents = '';
while (!feof($handle)) {
    $contents .= fread($handle, 8192);
}
fclose($handle);
?>

These examples demonstrate how fread() can be used for different file types and streaming scenarios in backend PHP development.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

BackendPHPexamplefile-handlingfread
Laravel Tech Community
Written by

Laravel Tech Community

Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.