Master PHP’s fread(): Read Files Efficiently with Code Examples

This guide explains PHP's fread() function, its syntax, parameters, return values, optional offset usage, and provides a complete example demonstrating how to open, read, output, and close a file safely.

php Courses
php Courses
php Courses
Master PHP’s fread(): Read Files Efficiently with Code Examples

PHP is a widely used scripting language for web development, and it provides many built‑in functions for file handling, including the fread() function.

Syntax

string fread(resource $handle, int $length)

Parameter Description

$handle: An opened file pointer, typically obtained via fopen().

$length: The number of bytes to read; you can specify an exact size or a variable value such as 1K.

Return Value: The function returns the read content as a string (byte stream) or false on error.

Example

<?php
// Open the file
$handle = fopen('example.txt', 'r');

// Check if the file was opened successfully
if ($handle) {
    // Read the file content
    $content = fread($handle, filesize('example.txt'));
    // Output the file content
    echo $content;
    // Close the file
    fclose($handle);
} else {
    echo 'Unable to open file';
}
?>

The example first uses fopen() to open example.txt and stores the file pointer in $handle. It then calls filesize() to obtain the file size and passes that value to fread() to read the entire file. The content is output with echo, and finally the file is closed with fclose().

Note that fread() returns a byte stream, so you may need to process or decode it according to your specific requirements.

Additionally, fread() has an optional $offset parameter that allows you to specify the starting position for reading, enabling you to skip parts of the file and read from the middle.

Summary: The fread() function is a powerful PHP file‑handling tool that reads a specified length of data from an opened file, suitable for text, binary, or other file types, and can be combined with other functions to enhance PHP program flexibility and functionality.

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.

PHPTutorialfile-handlingfread
php Courses
Written by

php Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

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.