Using PHP fread() to Read Files: Syntax, Parameters, and Example
This article explains PHP's fread() function, covering its syntax, parameters ($handle, $length, optional $offset), return value, and provides a complete example showing how to open a file, read its contents, output them, and properly close the file.
PHP is a widely used scripting language for developing web applications. One of its built‑in functions for file handling is fread() . The fread() function allows us to read a specified length of content from an opened file.
Syntax:
string fread(resource $handle, int $length)Parameter description:
$handle: an opened file pointer. It can be obtained using fopen() and passed to fread() .
$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); on failure it returns false .
The following example demonstrates how to use fread() to read a file's contents:
<?php
// Open file
$handle = fopen('example.txt', 'r');
// Check if the file was opened successfully
if ($handle) {
// Read file content
$content = fread($handle, filesize('example.txt'));
// Output file content
echo $content;
// Close file
fclose($handle);
} else {
echo 'Unable to open file';
}
?>In the example, fopen() opens a file named example.txt and stores the returned file pointer in the $handle variable. filesize() obtains the file size, which is passed to fread() to specify how many bytes to read. The echo statement outputs the content read from the file, and fclose() closes the file.
Note that the data returned by fread() is a byte stream, so it may need appropriate processing depending on the specific requirements.
fread() also has an optional $offset parameter that specifies the starting position within the file. By providing an offset, you can skip some content and begin reading from the middle of the file.
In summary, fread() is a powerful PHP file‑handling function that can read text files, binary files, or other types of files. By using it correctly, you can improve the flexibility and functionality of your PHP programs.
Hope the example and explanation help you better understand and use fread() in your PHP development.
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.