【问题标题】:download a zip file from a url从 url 下载 zip 文件
【发布时间】:2012-01-31 03:59:03
【问题描述】:

我想使用 php 从 url 下载一些 zip 文件。 IE。 sitename.com/path/to/file/id/123 当您直接访问此网址时,您会收到文件下载提示。我尝试使用fopen()file_get_contents(),但这些都失败了。我已经完成的搜索涉及如何使 zip 文件可下载或如何从 sitename.com/path/to/file.zip 获取文件,但我的 url 没有 .zip 扩展名。

fopen ('url.com') or die('can not open');

浏览器显示打不开

【问题讨论】:

  • but these fail.您在尝试这些方法时收到了什么信息?请出示代码。
  • 应该使用http://url.com,如果它没有死但没有显示尝试回显
  • 这还不够。可能会有一系列问题。您是否看到任何输出(没有正确的标题会很奇怪)或错误消息? echo file_get_contents('http://url.com/file');

标签: php download zip


【解决方案1】:

该网址可能是一个可能会重定向您的脚本。改用 CURL

$fh = fopen('file.zip', 'w');
$ch = curl_init()
curl_setopt($ch, CURLOPT_URL, $url); 
curl_setopt($ch, CURLOPT_FILE, $fh); 
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // this will follow redirects
curl_exec($ch);
curl_close($ch);
fclose($fh);

【讨论】:

  • 压缩文件正在下载为空压缩文件。有什么想法可能是错的吗?
  • 这个答案不再有效。它只会创建一个空的 ZIP 文件。
  • 如果你得到一个空文件并且在服务器上 zip 可以工作,那么你可能需要设置一个内容长度。 header("内容长度:" .filesize($yourfile));
  • 如果有人也有只下载一部分数据的问题:给更多的时间! curl_setopt($ch, CURLOPT_TIMEOUT, (60*30)); // 30 minutes当然也允许脚本运行多久。
【解决方案2】:

对于这类事情,使用 readfile() 等更基本的函数可能更容易。

改编自an example at php.net

<?php
// We'll be outputting a ZIP
header('Content-type: application/zip');

// Use Content-Disposition to force a save dialog.
// The file will be called "downloaded.zip"
header('Content-Disposition: attachment; filename="downloaded.zip"');

// The ZIP source is in original.zip
readfile('original.zip');
?>

【讨论】:

  • 感谢为我工作。(从 url 下载 zip 文件)
猜你喜欢
  • 1970-01-01
  • 2012-03-14
  • 1970-01-01
  • 2014-05-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-10
相关资源
最近更新 更多