使用php从url下载zip文件

时间:2017-06-02 04:48:10

标签: php

它不是关于文件重复,

//无法使用代码,因为我分配了$ zip_url dynamic

function downloadZipFile($dynamic_url, $filepath){
//echo $dynamic_url;exit;
$zip_url          = $dynamic_url;
$destination_path = $filepath;
file_put_contents($destination_path, fopen($zip_url, 'r'));
 } 

//工作代码,但在这里我指定$ zip_url static

function downloadZipFile($dynamic_url, $filepath){
//echo $dynamic_url;exit;
$zip_url          = "http://training.costaclick.net/WAWS_1_9/Catalog/4dd946a8-32e6-43b8-a592-6596a4509ec5-out.zip";
$destination_path = $filepath;
file_put_contents($destination_path, fopen($zip_url, 'r'));
 } 

2 个答案:

答案 0 :(得分:0)

试用此代码:

$ch = curl_init();
$source = "http://someurl.com/afile.zip"; //$source = $dynamic_url
curl_setopt($ch, CURLOPT_URL, $source);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec ($ch);
curl_close ($ch);

$destination = "/sub_folder/". uniqid(time(), true) .".zip";
$file = fopen($destination, "w+");
fputs($file, $data);
fclose($file);

$source可以是url的动态值。 uniqid(time(), true)将生成随机文件名。在我们将它存储在$destination变量。

中指定的路径中

替代解决方案:

$zip_url          = "http://www.colorado.edu/conflict/peace/download/peace.zip";
$destination_path = "/var/www/html/files/".uniqid(time(), true)."zip";
file_put_contents($destination_path, fopen($zip_url, 'r'));

$zip_url将是动态zip网址,$destination_path将位于您本地计算机上。

注意:请确保您对目标路径文件夹拥有适当的权限。

答案 1 :(得分:0)

<?php // HTTP Headers for ZIP File Downloads
  // https://perishablepress.com/press/2010/11/17/http-headers-file-downloads/

  // set example variables
  $filename = "Inferno.zip";
  $filepath = "/var/www/domain/httpdocs/download/path/";

  // http headers for zip downloads
  header("Pragma: public");
  header("Expires: 0");
  header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
  header("Cache-Control: public");
  header("Content-Description: File Transfer");
  header("Content-type: application/octet-stream");
  header("Content-Disposition: attachment; filename=\"".$filename."\"");
  header("Content-Transfer-Encoding: binary");
  header("Content-Length: ".filesize($filepath.$filename));
  ob_end_flush();
  @readfile($filepath.$filename);
?>

reference link