array ( 0 => 'index.php', 1 => 'PHP Manual', ), 'head' => array ( 0 => 'UTF-8', 1 => 'zh', ), 'this' => array ( 0 => 'function.fread.php', 1 => 'fread', ), 'up' => array ( 0 => 'ref.filesystem.php', 1 => '文件系统函数', ), 'prev' => array ( 0 => 'function.fputs.php', 1 => 'fputs', ), 'next' => array ( 0 => 'function.fscanf.php', 1 => 'fscanf', ), 'alternatives' => array ( ), 'source' => array ( 'lang' => 'zh', 'path' => 'reference/filesystem/functions/fread.xml', ), ); $setup["toc"] = $TOC; $setup["toc_deprecated"] = $TOC_DEPRECATED; $setup["parents"] = $PARENTS; manual_setup($setup); ?>
(PHP 4, PHP 5, PHP 7, PHP 8)
fread — 读取文件(可安全用于二进制文件)
fread() 从文件指针
stream
读取最多
length
个字节。
该函数在遇上以下几种情况时停止读取文件:
length
个字节
返回所读取的字符串, 或者在失败时返回 false
。
示例 #1 一个简单的 fread() 例子
<?php
// get contents of a file into a string
$filename = "/usr/local/something.txt";
$handle = fopen($filename, "r");
$contents = fread($handle, filesize($filename));
fclose($handle);
?>
示例 #2 Binary fread() example
在区分二进制文件和文本文件的系统上(如 Windows)打开文件时,fopen() 函数的 mode 参数要加上 'b'。
<?php
$filename = "c:\\files\\somepic.gif";
$handle = fopen($filename, "rb");
$contents = fread($handle, filesize($filename));
fclose($handle);
?>
示例 #3 Remote fread() examples
当从任何不是普通本地文件读取时,例如在读取从远程文件或 popen() 以及 fsockopen() 返回的流时,读取会在一个包可用之后停止。这意味着应该如下例所示将数据收集起来合并成大块。
<?php
$handle = fopen("http://www.example.com/", "rb");
if (FALSE === $handle) {
exit("Failed to open stream to URL");
}
$contents = stream_get_contents($handle);
fclose($handle);
?>
<?php
$handle = fopen("http://www.example.com/", "rb");
$contents = '';
while (!feof($handle)) {
$contents .= fread($handle, 8192);
}
fclose($handle);
?>
注意:
如果只是想将一个文件的内容读入到一个字符串中,用 file_get_contents(),它的性能比上面的代码好得多。
注意:
Note that fread() reads from the current position of the file pointer. Use ftell() to find the current position of the pointer and rewind() to rewind the pointer position.