Backend Development 4 min read

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
// 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 content
echo $content;
// Close the file
fclose($handle);
} else {
echo 'Unable to open file';
}
?>

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.

backendTutorialfile 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

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