php的fread函数的一个巨大的坑

时间:2022-08-10 14:42:48

先看看fread的manual,如下:

http://php.net/manual/en/function.fread.php

fread() reads up to length bytes from the file pointer referenced by handle. Reading stops as soon as one of the following conditions is met:

  • length bytes have been read
  • EOF (end of file) is reached
  • a packet becomes available or the socket timeout occurs (for network streams)
  • if the stream is read buffered and it does not represent a plain file, at most one read of up to a number of bytes equal to the chunk size (usually 8192) is made; depending on the previously buffered data, the size of the returned data may be larger than the chunk size.

中文:

fread() 从文件指针 file 读取最多 length 个字节。该函数在读取完最多 length 个字节数,或到达 EOF 的时候,或(对于网络流)当一个包可用时,或(在打开用户空间流之后)已读取了 8192 个字节时就会停止读取文件,视乎先碰到哪种情况。

返回所读取的字符串,如果出错返回 false。

结论:大家要注意上面红色的地方,一定要判断fread的返回值。我就是没有看文档,以为需要多少,就能读到多少。结果当读取的字节数过大时(与chunk size有关,好像是4K),各种出错。(这也与python的误导有关,因为python的sys.stdin.read就不是这样,我是参考了python的写法)

参考如下代码:

$v_content = '';
while (strlen($v_content) < $v_len[1]) {
$v_content .= fread(STDIN, $v_len[1] - strlen($v_content));
}