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

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

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

Syntax: string fread(resource $handle, int $length) Parameters: $handle: an opened file pointer obtained from fopen(). $length: the number of bytes to read; you can specify an exact size or a variable value such as "1K". $offset (optional): the position in the file where reading should start.

Return value: the function returns the read bytes as a string, or false on error.

Example usage:

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

The script first opens example.txt with fopen(), stores the pointer in $handle, then uses filesize() to determine how many bytes to read and passes that value to fread(). The read content is echoed, 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.

If you need to start reading from a specific position, you can provide the optional $offset argument to skip ahead in the file.

In summary, fread() is a powerful PHP function for reading a specified length of data from an opened file, suitable for text, binary, or other file types, and can greatly enhance file‑handling capabilities in PHP applications.

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.

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