如何用PHP下载多个大文件?

时间:2015-12-30 16:25:27

标签: php

我曾尝试使用zip php扩展程序下载多个大文件,但我没有成功,因为服务器总是超时。

$revfiles = $_POST['file'];
if(empty($revfiles))
{
  echo("You didn't select any file.");
}
else
{
  $zip = new ZipArchive();
  $filename = $_SERVER['DOCUMENT_ROOT'] . "/tmp/test70.zip";
  if ($zip->open($filename, ZipArchive::CREATE)!==TRUE) {
    exit("cannot open <$filename>\n");
  }
  $N = count($revfiles);
  for($i=0; $i < $N; $i++)
  {
    if($zip->addFile($_SERVER['DOCUMENT_ROOT'] . "/" . $revfiles[$i], strrchr($revfiles[$i], "/"))!==TRUE){
      //echo("ERROR");
    }
  }
  $zip->close();    

  header("Content-type: application/zip"); 
  header("Content-Disposition: attachment; filename=test70.zip"); 
  header("Pragma: no-cache"); 
  header("Expires: 0"); 
  readfile("$filename");
  exit;
}
[30-Dec-2015 12:32:17 Europe/Berlin] PHP Fatal error:  Maximum execution time of 30 seconds exceeded in /.../file.php on line 37

在我禁用此脚本的时间限制后,我收到此错误:

[30-Dec-2015 16:38:29 Europe/Berlin] PHP Fatal error:  Allowed memory size of 524288000 bytes exhausted (tried to allocate 660656128 bytes) in /.../file.php on line 43

有人知道用php下载多个大文件的另一种方法吗?

2 个答案:

答案 0 :(得分:0)

看起来您需要更改内存和文件上传大小限制以及脚本执行时间。所有都可以在php.ini文件中更改,但我会通过脚本更改最大执行时间脚本,而不是为所有PHP请求更改它。

最长执行时间

更改执行时间可以通过两种方式完成(在脚本中)...

1)将下面的行放在脚本的顶部。这将允许脚本无限期运行。如果您想更精细地控制每个文件上传多长时间,请使用第二个建议。

<div class='printchatbox' id='printchatbox'></div>
<input type='text' name='fname' value="Kees" class='chatinput' id='chatinput'>

2)在循环中使用相同的行,而不是在脚本的开头,但是将秒数从0更改为要为每个文件下载的长度。这是有效的,因为set_time_limit()每次被调用时都会将执行时间重置为零。

因此,如果您想让每个文件都有30秒,那么您的循环将看起来像......

set_time_limit(0);

MEMORY&amp;最大文件大小

您应该更改三种设置:

  • 的upload_max_filesize
  • 的post_max_size
  • memory_limit的

如果您使用的网站主机无法访问php.ini文件,那么您可以在脚本或htaccess文件中更改这些内容(根据需要调整值)... < / p>

PHP文件

for($i=0; $i < $N; $i++)
{
    set_time_limit(30);
    if($zip->addFile($_SERVER['DOCUMENT_ROOT'] . "/" . $revfiles[$i], strrchr($revfiles[$i], "/"))!==TRUE){
        //echo("ERROR");
    }
}

.htaccess文件:

ini_set('upload_max_filesize', '64M');
ini_set('post_max_size', '64M');
ini_set('memory_limit', '32M');

如果您有权访问php.ini文件,只需更改那里的设置即可!

答案 1 :(得分:0)

您希望以块的形式传输文件。这是关于此问题的SO帖子:Download File to server from URL

file_put_contents("Tmpfile.zip", fopen("http://someurl/file.zip", 'r'));
相关问题