Downloading large files using PHP

戏子无情 提交于 2020-01-06 23:46:08

问题


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

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 ...

Thanks


回答1:


I believe you need:

curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);

to make curl_exec() return the data, and:

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

to get the file actually written.




回答2:


As mentioned in http://php.net/manual/en/function.curl-setopt.php :

CURLOPT_RETURNTRANSFER: TRUE to return the transfer as a string of the return value of curl_exec() instead of outputting it out directly.

So you can simply add this line before your curl_exec line:

curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);

and you will have the content in $data variable.




回答3:


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


来源:https://stackoverflow.com/questions/15129523/downloading-large-files-using-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!