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

This article explains PHP’s fread() function, its syntax, parameters, return values, and provides a complete example showing how to open a file, read its contents, output them, and properly close the handle, including optional offset usage.

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 applications, and it provides many built-in functions for file handling, including the fread() function.

Syntax

string fread(resource $handle, int $length)

$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');

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

In this example, fopen() opens example.txt and stores the file pointer in $handle. The filesize() function obtains the file size, which is passed to fread() to specify how many bytes to read. The echo statement outputs the read content, and fclose() closes the file.

Note that fread() returns a byte stream, so you may need to process 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. By using it appropriately, you can handle text, binary, or other file types efficiently, enhancing the flexibility and functionality of your PHP programs.

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.

BackendPHPTutorialfile-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.