使用 cURL 下载 ZIP 文件

use*_*329 1 php zip fopen curl

我正在尝试使用 cURL 从给定的 URL 下载 ZIP 文件。我从供应商那里收到了一个 URL,我应该在其中下载 ZIP 文件。但是每次我尝试下载 ZIP 文件时,我都会看到一个页面,说我没有登录。

我应该从中获取文件的网址如下所示:

https://www.tyre24.com/nl/nl/user/login/userid/USERID/password/PASSWORD/page/L2V4cG9ydC9kb3dubG9hZC90L01nPT0vYy9NVFE9Lw==
Run Code Online (Sandbox Code Playgroud)

在这里您可以看到 USERID 和 PASSWORD 是填充了正确数据的变量。奇怪的是,如果我在浏览器中输入 URL,它似乎可以工作,则 zip 文件正在下载。

但是每次我用 cURL 调用那个 URL 时,我似乎得到一个不正确的登录页面。有人能告诉我我做错了什么吗?

似乎给定的 URL 后面有一个重定向,这就是我放入 cURL 调用的原因: curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

这是我的代码:

set_time_limit(0);

//File to save the contents to
$fp = fopen ('result.zip', 'w+');

$url = "https://www.tyre24.com/nl/nl/user/login/userid/118151/password/5431tyre24/page/L2V4cG9ydC9kb3dubG9hZC90L01nPT0vYy9NVFE9Lw==";

//Here is the file we are downloading, replace spaces with %20
$ch = curl_init(str_replace(" ","%20",$url));

curl_setopt($ch, CURLOPT_TIMEOUT, 50);

//give curl the file pointer so that it can write to it
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

$data = curl_exec($ch);//get curl response

//done
curl_close($ch);
Run Code Online (Sandbox Code Playgroud)

难道我做错了什么?

Rom*_*est 7

要通过使用以下方法之一从外部源下载zip文件CURL:

第一种方法:

function downloadZipFile($url, $filepath){
     $ch = curl_init($url);
     curl_setopt($ch, CURLOPT_HEADER, 1);
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
     curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
     curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);
     $raw_file_data = curl_exec($ch);

     if(curl_errno($ch)){
        echo 'error:' . curl_error($ch);
     }
     curl_close($ch);

     file_put_contents($filepath, $raw_file_data);
     return (filesize($filepath) > 0)? true : false;
 }

downloadZipFile("http://www.colorado.edu/conflict/peace/download/peace_essay.ZIP", "result.zip");
Run Code Online (Sandbox Code Playgroud)

几点意见:

  • 要从远程源取回数据,您必须设置 CURLOPT_RETURNTRANSFER选项
  • 而不是随后调用fopen...fwite函数,你可以使用file_put_contents它更方便

result.zip这是几分钟前使用上述方法下载的屏幕截图:

结果

第二种方法:

function downloadZipFile($url, $filepath){
     $fp = fopen($filepath, 'w+');
     $ch = curl_init($url);

     curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
     curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
     //curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, false );
     curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
     curl_setopt($ch, CURLOPT_FILE, $fp);
     curl_exec($ch);

     curl_close($ch);
     fclose($fp);

     return (filesize($filepath) > 0)? true : false;
 }
Run Code Online (Sandbox Code Playgroud)