通过cURL将文件从其他服务器传输到用户

时间:2014-07-02 23:54:39

标签: php curl

我用了好方法?文件很大,可能高达几GB。请指教。 $直接 是一个大文件的地址。该脚本支持恢复。

$contentLength = getParamFromHeaders('Content-Length', $fileHeaders);
$contentType = getParamFromHeaders('Content-Type', $fileHeaders);
$contentDisposition = getParamFromHeaders('Content-Disposition', $fileHeaders);

if (!$contentLength || !$contentType || !$contentDisposition) {
    http_response_code(403);
    echo 'error ' . __LINE__;
    exit;
}

发送:

header('Cache-Control: public');
header('Content-Transfer-Encoding: binary');
header('Content-Type: ' . $contentType);
header('Content-Disposition: ' . $contentDisposition);
header('Accept-Ranges: bytes');

if (isset($_SERVER['HTTP_RANGE'])) {

    preg_match('#^bytes\=(\d*)\-(\d*)$#is', @$_SERVER['HTTP_RANGE'], $range);
    $rangeStart = (int) $range[1];
    $rangeEnd = (int) $range[2];

    if ($rangeEnd < $rangeStart) {
        $rangeEnd = $contentLength - 1;
    }

    $newContentLength = $rangeEnd - $rangeStart + 1;

    header("HTTP/1.1 206 Partial Content");
    header('Content-Range: bytes ' . $rangeStart . '-' . $rangeEnd . '/' . $contentLength);
    header('Content-Length: ' . $newContentLength);
} else {

    $rangeStart = 0;
    $rangeEnd = $contentLength -1;
    header('HTTP/1.1 200 OK');
    header('Content-Length: ' . $contentLength);
}

与其他服务器连接:

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $direct);
curl_setopt($ch, CURLOPT_RANGE, $rangeStart . '-'.$rangeEnd);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
curl_setopt($ch, CURLOPT_BUFFERSIZE, 8096);
curl_exec($ch);
curl_close($ch);

发送给用户:

while (!empty($result)) {
    echo $result;
}

我是否需要在php.ini中进行更改?

0 个答案:

没有答案
相关问题