簡體   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