Using PHP fread() to Read Files: Syntax, Parameters, and Example
This article explains PHP's fread() function, covering its syntax, parameters, return values, optional offset argument, and provides a complete example that opens a file, reads its contents based on size, outputs the data, and closes the handle.
PHP is a widely used scripting language for web development, and its built-in function fread() allows reading a specified length of data from an opened file.
Syntax: string fread(resource $handle, int $length)
Parameters: $handle is a file pointer obtained via fopen() ; $length is the number of bytes to read. The function returns the read data as a string or false on error.
Example code demonstrates opening a file, using filesize() to determine length, reading with fread() , echoing the content, and closing the file.
<?php
// 打开文件
$handle = fopen('example.txt', 'r');
// 检查文件是否成功打开
if ($handle) {
// 读取文件内容
$content = fread($handle, filesize('example.txt'));
// 输出文件内容
echo $content;
// 关闭文件
fclose($handle);
} else {
echo '无法打开文件';
}
?>The article also notes that fread() returns a byte stream that may need further processing, and mentions an optional $offset parameter for reading from a specific position within the file.
In summary, fread() is a powerful PHP file‑handling function suitable for reading text, binary, or other file types, and proper use can enhance the flexibility and functionality of PHP programs.
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.