使用PHP下载大文件 [英] Downloading large files using PHP

查看:72
本文介绍了使用PHP下载大文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am using following code to download files from some remote server using 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时为垃圾字符).

but instead of downloading and saving the file in the directory it is showing the file contents (junk characters as file is zip) directly on the browser only.

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

I guess it might be an issue with header content, but not know exactly ...

谢谢

推荐答案

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

Use the following function that includes error handling.

// 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;
    }
}

这篇关于使用PHP下载大文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆