繁体   English   中英

使用外部链接PHP的readfile()进行可恢复的下载

[英]Make resumable downloads with readfile() of external link PHP

我有以下代码:

if  (isset($_GET['file']) && isset($_GET['name']))
{

    $ch = curl_init($file);
    curl_setopt($ch, CURLOPT_NOBODY, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HEADER, true);

    $data = curl_exec($ch);
    curl_close($ch);

    if (preg_match('/Content-Length: (\d+)/', $data, $matches)) 
    {
        // Contains file size in bytes
        $contentLength = (int)$matches[1];
    }

    header("Content-type: application/x-file-to-save");
    header("Content-Disposition: attachment; filename=".$_REQUEST['name']);
    header('Content-Length: ' . $contentLength);
    header('Content-Transfer-Encoding: binary');
    header('Accept-Ranges: bytes');
    header('Connection: Keep-Alive');
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0', false);
    header('Cache-Control: private', false);

    readfile($file);
}

问题是$ file位于另一台服务器上。 如何启用恢复此下载? 谢谢!

修改卷发使其也拉入身体(删除NOBODY选项)

然后,您可以将返回的内容($ data)拆分为标题和正文-拆分为第一行空白(连续查找两个回车符-上面的内容为标题,下面的内容为正文)。 将它们放入变量$ header和$ body。

在$ header上运行您的preg_match。

要输出其余内容,只需“ echo $ body”或substr($ body,$ startpos)即可恢复下载。


断点续传下载:如果文件很大,则可能要在本地缓存。 (即,将“ $ body”保存到本地文件,然后在本地文件上使用readfile。然后,您可以通过打开文件(fopen)并转到正确的位置(fseek)并阅读(读取)来处理可恢复的下载/一旦找到起点,fpassthru也应该做同样的事情。

另外,如果您尝试假冒他人的内容,请先获得许可;)(否则为什么不直接将用户定向到该其他URL并节省带宽出入)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM