fread a lot slower for downloads than readfile

落爺英雄遲暮 提交于 2019-12-01 19:32:44

Use stream_context_create() and stream_get_contents()

$context = stream_context_create();
$file = fopen($url, 'rb', FALSE, $context);
while(!feof($file))
{
    //usleep(1000000);
    echo stream_get_contents($file, 2014);
}

You could also try making the file read length larger and putting in a usleep() to slow execution. The stream functions seem to be recommended over fread for the latest version of PHP anyway. You might want to also prepend an @ in front of the fread() or stream_get_contents() to suppress any errors, at least in production. Without it, and a little mishap, and you have a corrupted file.

It might be buffering (or perhaps even rate-limiting) somewhere in PHP or Apache. Try changing:

while(!feof($file)) {
   echo fread($file, 2014);
}

To:

while(!feof($file)) {
   $s=fread($file, 2014);
   if($s===false)break;  //Crude
   echo $s;
   @ob_flush();@flush();
}

(The @ prefix is because they might complain about empty buffers.)

As mr.freshwater said, you ought to have error-checking on your fread call, so I've added something basic above.

The reason is 2014. OS gets 4096 byte data portion very fast then others. But if you write 2014, then OS tries to read data from file by one byte to calculate it. That's why it takes so long time. Change 2014 to 4096

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!