如何使用PHP下载大文件(低内存使用)

10

我需要使用PHP下载大文件(1xx MB)。

如何在不浪费内存(RAM)的情况下进行下载而无需使用临时文件?

当我使用

$something=file_get_contents('http://somehost.example/file.zip');
file_put_contents($something,'myfile.zip');

我需要有足够的内存来存储那个文件的大小。

也许可以用其他方式下载它吗?

例如,将其分成若干部分(例如1024字节),写入磁盘,并重复下载另一部分,直到完全下载该文件?


https://dev59.com/5HA65IYBdhLWcg3wqQc8 - Keyne Viana
可能是使用curl下载大文件的重复问题。 - dynamic
2个回答

37

逐个小块地复制文件

/**
 * Copy remote file over HTTP one small chunk at a time.
 *
 * @param $infile The full URL to the remote file
 * @param $outfile The path where to save the file
 */
function copyfile_chunked($infile, $outfile) {
    $chunksize = 10 * (1024 * 1024); // 10 Megs

    /**
     * parse_url breaks a part a URL into it's parts, i.e. host, path,
     * query string, etc.
     */
    $parts = parse_url($infile);
    $i_handle = fsockopen($parts['host'], 80, $errstr, $errcode, 5);
    $o_handle = fopen($outfile, 'wb');

    if ($i_handle == false || $o_handle == false) {
        return false;
    }

    if (!empty($parts['query'])) {
        $parts['path'] .= '?' . $parts['query'];
    }

    /**
     * Send the request to the server for the file
     */
    $request = "GET {$parts['path']} HTTP/1.1\r\n";
    $request .= "Host: {$parts['host']}\r\n";
    $request .= "User-Agent: Mozilla/5.0\r\n";
    $request .= "Keep-Alive: 115\r\n";
    $request .= "Connection: keep-alive\r\n\r\n";
    fwrite($i_handle, $request);

    /**
     * Now read the headers from the remote server. We'll need
     * to get the content length.
     */
    $headers = array();
    while(!feof($i_handle)) {
        $line = fgets($i_handle);
        if ($line == "\r\n") break;
        $headers[] = $line;
    }

    /**
     * Look for the Content-Length header, and get the size
     * of the remote file.
     */
    $length = 0;
    foreach($headers as $header) {
        if (stripos($header, 'Content-Length:') === 0) {
            $length = (int)str_replace('Content-Length: ', '', $header);
            break;
        }
    }

    /**
     * Start reading in the remote file, and writing it to the
     * local file one chunk at a time.
     */
    $cnt = 0;
    while(!feof($i_handle)) {
        $buf = '';
        $buf = fread($i_handle, $chunksize);
        $bytes = fwrite($o_handle, $buf);
        if ($bytes == false) {
            return false;
        }
        $cnt += $bytes;

        /**
         * We're done reading when we've reached the conent length
         */
        if ($cnt >= $length) break;
    }

    fclose($i_handle);
    fclose($o_handle);
    return $cnt;
}

请根据自己的需要调整$chunksize变量。这仅经过了轻微测试,由于多种原因,它很容易出现错误。

用法:

copyfile_chunked('http://somesite.com/somefile.jpg', '/local/path/somefile.jpg');

代码看起来不错,但是以那种方式允许用户打开远程文件是不可能的。也许你有类似使用 fsockopen 的代码? - marc
1
如果 PHP 中的 allow_url_fopen 指令已打开,它应该可以工作。但我会更新我的示例以显示套接字的使用。 - mellowsoon
相信您在 fsockopen 中的 $errorcode$errorstr 是颠倒的。 - srcspider
我已经启用了allow_url_fopen,但仍然出现500错误。 - Kaspar L. Palgi

10

你可以使用exec()调用wget,这将导致最低的内存使用。

<?php
 exec("wget -o outputfilename.tar.gz http://pathtofile/file.tar.gz")
?>

您还可以尝试使用 fopen()fread()fwrite()。这样,您每次只需将x个字节下载到内存中。


这对于大约1GB以上的文件不起作用。 - SagarPPanchal

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接