繁体   English   中英

使用PHP下载大文件

[英]Downloading large files using PHP

我正在使用以下代码使用php从某些远程服务器下载文件

//some php page parsing code
$url  = 'http://www.domain.com/'.$fn;
$path = 'myfolder/'.$fn;
$fp = fopen($path, 'w');
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_FILE, $fp);
$data = curl_exec($ch);
curl_close($ch);
fclose($fp);
// some more code

但不是直接将文件下载并保存到目录中,而是直接在浏览器中显示文件内容(文件为zip时为垃圾字符)。

我想这可能是标题内容的问题,但不完全清楚...

谢谢

我相信您需要:

curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);

使curl_exec()返回数据,并且:

$data = curl_exec($ch);
fwrite($fp, $data);

获取实际写入的文件。

http://php.net/manual/en/function.curl-setopt.php中所述

CURLOPT_RETURNTRANSFER:真 ,将传输作为curl_exec()返回值的字符串返回,而不是直接输出。

因此,您只需在curl_exec行之前添加以下行:

curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);

并且您的内容将在$ data变量中。

使用以下包含错误处理的功能。

// Download and save a file with curl
function curl_dl_file($url, $dest, $opts = array())
{
    // Open the local file to save. Suppress warning
    // upon failure.
    $fp = @fopen($dest, 'w+');

    if (!$fp)
    {
        $err_arr = error_get_last();
        $error = $err_arr['message'];
        return $error;
    }

    // Set up curl for the download
    $ch = curl_init($url);

    if (!$ch)
    {
        $error = curl_error($ch);
        fclose($fp);
        return $error;
    }

    $opts[CURLOPT_FILE] = $fp;

    // Set up curl options
    $failed = !curl_setopt_array($ch, $opts);

    if ($failed)
    {
        $error = curl_error($ch);
        curl_close($ch);
        fclose($fp);
        return $error;
    }

    // Download the file
    $failed = !curl_exec($ch);

    if ($failed)
    {
        $error = curl_error($ch);
        curl_close($ch);
        fclose($fp);
        return $error;
    }

    // Close the curl handle.
    curl_close($ch);

    // Flush buffered data to the file
    $failed = !fflush($fp);

    if ($failed)
    {
        $err_arr = error_get_last();
        $error = $err_arr['message'];
        fclose($fp);
        return $error;
    }

    // The file has been written successfully at this point. 
    // Close the file pointer
    $failed = !fclose($fp);

    if (!$fp)
    {
        $err_arr = error_get_last();
        $error = $err_arr['message'];
        return $error;
    }
}

暂无
暂无

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

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