duan39779 2014-05-04 15:36
浏览 111

PHP fread()块长度未正确考虑

I want to send an external MP4 file in chunks of 1 MB each to a user. With each chunk I update a database entry to keep track of the download progress. I use fread() to read the file in chunks. Here is the stripped down code:

$filehandle = fopen($file, 'r');

while(!feof($filehandle)){
  $buffer = fread($filehandle, 1024*1024);

  //do some database stuff

  echo $buffer;
  ob_flush();
  flush(); 
}

However, when I check the chunk size at some iteration inside the while loop, with

$chunk_length = strlen($buffer);
die("$chunk_length");

I do never get the desired chunk size. It fluctates somewhere around 7000 - 8000 bytes. Nowhere near 1024*1024 bytes. When I decrease the chunk size to a smaller number, for example 1024 bytes, it works as expected.

  • 写回答

1条回答 默认 最新

  • dslfq06464 2015-01-06 10:03
    关注

    According to the PHP fread() manual:

    "When reading from anything that is not a regular local file, such as streams returned when reading remote files or from popen() and fsockopen(), reading will stop after a packet is available."

    In this case I opened a remote file. Apparently, this makes fread() stop not at the specified length, but when the first package has arrived.

    I wanted to keep track of a download of an external file. If you to do this (or keep track of an upload), use CURL instead:

    curl_setopt($curl_handle, CURLOPT_NOPROGRESS, false);
    curl_setopt($curl_handle, CURLOPT_PROGRESSFUNCTION, 'callbackFunction');
    
    function callbackFunction($download_size, $downloaded, $upload_size, $uploaded){
      //do stuff with the parameters
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题