Using PHP fread() to Read Files: Syntax, Parameters, and Example

This article explains PHP’s fread() function, covering its syntax, parameters, return values, and provides a complete example demonstrating how to open a file, read its contents, handle errors, and close the file, along with notes on optional offset usage.

php Courses
php Courses
php Courses
Using PHP fread() to Read Files: Syntax, Parameters, and Example

PHP is a widely used scripting language for web development, and its built‑in fread() function allows developers to read a specified length of data from an opened file.

Syntax: string fread(resource $handle, int $length) Parameters: $handle : an opened file pointer obtained from fopen(). $length : the number of bytes to read; it can be a fixed size or a variable such as "1K".

Return value: the function returns the read data as a string (byte stream) on success, or false on failure.

Example usage:

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

In the example, fopen() opens example.txt and returns a file pointer stored in $handle. filesize() obtains the file size, which is passed to fread() to specify how many bytes to read. The content is then echoed, and the file is closed with fclose().

Note that fread() returns a byte stream, so the data may need further processing depending on the application. The function also accepts an optional $offset parameter to start reading from a specific position within the file.

In summary, fread() is a powerful PHP file‑handling function that can read any type of file—text, binary, or otherwise—by specifying the desired length, and with optional offset support it provides flexible file‑reading capabilities for PHP developers.

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.