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 is a widely used scripting language for web development, and it provides many built‑in functions for file handling, including the fread() function.
Syntax: <code>string fread(resource $handle, int $length)</code>
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:
<code><?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/>?></code>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.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.