douyi9787 2015-01-19 16:19
浏览 281
已采纳

PHP Curl直接下载/流式部分内容

I want to send/stream Files from an other Website/Webadress directly to the user, without storing the Files on my Server. The Files are Archives about 100MB to 1GB

The download with one thread works fine. Here is my Code:

$ch5 = curl_init();
if (isset($_SERVER['HTTP_RANGE'])) {
    //http://stackoverflow.com/questions/157318/resumable-downloads-when-using-php-to-send-the-file
    preg_match('/bytes=(\d+)-(\d+)?/', $_SERVER['HTTP_RANGE'], $matches);
    $offset = intval($matches[1]);
    $end = $matches[2] || $matches[2] === '0' ? intval($matches[2]) : $size - 1;
    curl_setopt($ch5, CURLOPT_RANGE, "$offset-$end");
}
curl_setopt($ch5, CURLOPT_URL, $direct_link);
curl_setopt($ch5, CURLOPT_TIMEOUT, 3550); 
curl_setopt($ch5, CURLOPT_CONNECTTIMEOUT, 15); 
curl_setopt($ch5, CURLOPT_HEADERFUNCTION, 'readHeader');
curl_exec($ch5);
$dlsize = curl_getinfo($ch5,CURLINFO_SIZE_DOWNLOAD );
$time = curl_getinfo($ch5,CURLINFO_TOTAL_TIME);
curl_close($ch5);

function readHeader($ch, $header) // Send header from the Downloaded file to the User
{
    header($header);
    return strlen($header);
}

The problem is that PHP Download the complete file if the request contains an Range like "Range: bytes=0-" and sending it to the user. But the User download much slower(Cause slower download speed) then downloading it to my Server, but if the file is completely downloaded, the file isn't available on the external Server. And when the Client make an Range Request for the second half or something else the Request goes to the external Server and the file isn't available, cause it is already completely downloaded by the first request, but I cant access the Data or is there a way to get these Data, without saving them on my disk?

I want to save Bandwidth an want to give users the possibility to make Range Requests. So PHP should only download the amount the user really want to download or make a direct connection between the external Server and User.

Actually I am using nginx/1.6.2 and PHP 5.5.20-1 on Ubuntu 12.04.5

  • 写回答

1条回答 默认 最新

  • drf21989 2016-10-19 10:49
    关注

    I solved my problem by using nginx with X-Sendfile/X-Accel-Redirect . More Information here: wiki.nginx.org/XSendfile

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥30 BC260Y用MQTT向阿里云发布主题消息一直错误
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退