I had a fread script that hanged forever (from php manual):
<?php
$fp = fsockopen("example.host.com", 80);
if (!$fp) {
echo "$errstr ($errno)<br />\n";
} else {
fwrite($fp, "Data sent by socket");
$content = "";
while (!feof($fp)) { //This looped forever
$content .= fread($fp, 1024);
}
fclose($fp);
echo $content;
}
?>
The problem is that sometimes end of streaming is not marked by EOF nor a fixed mark, that's why this looped forever. This caused me a lot of headaches...
I solved it using the stream_get_meta_data function and a break statement as the following shows:
<?php
$fp = fsockopen("example.host.com", 80);
if (!$fp) {
echo "$errstr ($errno)<br />\n";
} else {
fwrite($fp, "Data sent by socket");
$content = "";
while (!feof($fp)) {
$content .= fread($fp, 1024);
$stream_meta_data = stream_get_meta_data($fp); //Added line
if($stream_meta_data['unread_bytes'] <= 0) break; //Added line
}
fclose($fp);
echo $content;
}
?>
Hope this will save a lot of headaches to someone.
(Greetings, from La Paz-Bolivia)
PHP fread() 函数
定义和用法
fread() 函数读取文件(可安全用于二进制文件)。
语法
fread(file,length)
参数 | 描述 |
---|---|
file | 必需。规定要读取打开文件。 |
length | 必需。规定要读取的最大字节数。 |
说明
fread() 从文件指针 file 读取最多 length 个字节。该函数在读取完最多 length 个字节数,或到达 EOF 的时候,或(对于网络流)当一个包可用时,或(在打开用户空间流之后)已读取了 8192 个字节时就会停止读取文件,视乎先碰到哪种情况。
返回所读取的字符串,如果出错返回 false。
提示和注释
提示:如果只是想将一个文件的内容读入到一个字符串中,请使用 file_get_contents(),它的性能比 fread() 好得多。
例子
例子 1
从文件中读取 10 个字节:
<?php $file = fopen("test.txt","r"); fread($file,"10"); fclose($file); ?>
例子 2
读取整个文件:
<?php $file = fopen("test.txt","r"); fread($file,filesize("test.txt")); fclose($file); ?>