简体   繁体   English

在PHP中创建ZIP文件会出现浏览器错误,而不是脚本错误

[英]Creating ZIP File in PHP coming up with Browser errors, not Script errors

I created a code to backup an entire website & automatically download it on a single click. 我创建了一个代码来备份整个网站,然后单击一下即可自动下载。 Here is what my code looks like: 这是我的代码:

if (file_exists("file.zip")) {
  unlink("file.zip");
}
$folder_array = array();
$file_array = array();
function listFolderFiles($dir){
  global $folder_array;
  global $file_array;
  $ffs = scandir($dir);
  foreach($ffs as $ff){
    if ($ff != '.' && $ff != '..') {
      if (is_dir($dir.'/'.$ff)) {
        $new_item = "$dir/$ff";
        $new_item = str_replace('..//','',$new_item);
        if ($new_item !== "stats") {
          array_push($folder_array, $new_item);
          listFolderFiles($dir.'/'.$ff);
        }
      }
      else {
        $new_item = "$dir/$ff";
        $new_item = str_replace('..//','',$new_item);
        if (($new_item !== "stats/logs") && ($new_item !== "stats/")) {
          array_push($file_array, $new_item);
        }
      }
    }
  }
}
listFolderFiles('../');
$zip = new ZipArchive;
if ($zip->open('file.zip', true ? ZIPARCHIVE::OVERWRITE:ZIPARCHIVE::CREATE) === TRUE) {
  foreach($folder_array as $folder) {
    $zip->addEmptyDir($folder);
  }
  foreach($file_array as $key => $file) {
    $file_path = "../$file";
    $zip->addFile($file_path, $file);
  }
}
$zip->close();
$file = "file.zip";
chmod("$file", 0700);
header("Content-type: application/zip");
header("Content-Disposition: attachment; filename=". $file);
readfile($file);

Now this code was working good for awhile, but it seems today it doesn't want to work. 现在这段代码已经运行了好一阵子,但是今天看来它并不想运行。 The thing is, it's not a PHP script error. 事实是,这不是PHP脚本错误。 I've checked my error logs and nothing is showing up. 我检查了我的错误日志,没有任何显示。 It appears to be a browser error, but each browser displays a different message: 它似乎是浏览器错误,但每个浏览器都会显示不同的消息:

Chrome says "This webpage is not available" Firefox says "The connection was reset" Internet Explorer says "This page can't be displayed" Chrome说“此网页不可用”,Firefox说“连接已重置”,Internet Explorer说“无法显示此页面”

Even though these errors come up, the ZIP file is still being created and I can download it from the server. 即使出现这些错误,ZIP文件仍在创建中,我可以从服务器下载它。

Here is a list of things I've tried after extensive research: 这是经过广泛研究后我尝试过的事情清单:

1) I removed the code to have the ZIP file download automatically (all code written after I close the ZIP file). 1)我删除了自动下载ZIP文件的代码(关闭ZIP文件后编写的所有代码)。 Still get the browser errors. 仍然出现浏览器错误。

2) I read that it's possible too many files are getting opened and its going over my limit. 2)我读到有可能打开了太多文件,并且超出了我的限制。 I added to the code to close and reopen the ZIP file after every 200 files. 我添加到代码中,以每200个文件关闭并重新打开ZIP文件。 Still didn't work. 还是没用。

3) I limited the amount of files to ZIP. 3)我将文件数量限制为ZIP。 Everything was working fine below 500. Between 500 to 1,000 files, the code would work a partial amount of the time. 低于500,一切都可以正常工作。在500到1,000个文件之间,代码会在部分时间内工作。 Sometimes it would go through fine, the others it would give me the browser error. 有时它会很好,其他的会给我浏览器错误。 After 1,000 or so it just wouldn't work properly at all. 1000左右后,它将根本无法正常工作。

The hosting is through GoDaddy. 托管是通过GoDaddy进行的。

PHP Version is 5.2.17 PHP版本是5.2.17

max_execution_time is set at 240 (the code never goes this long, usually only takes about 30 sec to run) max_execution_time设置为240(代码从不会花那么长时间,通常只需要30秒即可运行)

memory_limit is set at 500M (more than twice the size of all the files combined) memory_limit设置为500M(超过所有文件总和的两倍)

I'm at a loss, I really don't know what is going on because this code was working just fine for 1,500 files a few weeks ago. 我不知所措,我真的不知道发生了什么,因为几周前这段代码对1,500个文件运行良好。 And again, the ZIP file is still being created, there are no PHP errors and it's only the Browsers that are coming back with these errors. 同样,ZIP文件仍在创建中,没有PHP错误,只有浏览器返回了这些错误。

I don't know what's wrong with your code, but I'm using the code below and it has been working forever with me. 我不知道您的代码有什么问题,但是我正在使用下面的代码,并且它一直在与我合作。

function create_zip($path, $save_as)
{
    if (!extension_loaded('zip'))
        throw new ErrorException('Extension ZIP has not been compiled or loaded in php.');
    else if(!file_exists($path))
        throw new ErrorException('The file/path you want to zip doesn\'t exist!');


    $zip = new ZipArchive();
    if (!$zip->open($save_as, ZIPARCHIVE::CREATE))
        throw new ErrorException('Could not create zip file!');

    $ignore = array('.','..');
    if($path == dirname($save_as))
        $ignore[] = basename($save_as);

    $path = str_replace('\\', '/', realpath($path));

    if (is_dir($path)) {
        $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path), RecursiveIteratorIterator::SELF_FIRST);
        foreach ($files as $file) {
            $file = str_replace('\\', '/', $file);

            if( in_array(substr($file, strrpos($file, '/')+1),$ignore )) continue;

            $file = realpath($file);
            if (is_dir($file)) {
                $zip->addEmptyDir(str_replace($path . '/', '', $file . '/'));
            }
            else if (is_file($file)) {
                $zip->addFromString(str_replace($path . '/', '', $file), file_get_contents($file));
            }
        }
    }
    else if (is_file($path)) {
        $zip->addFromString(basename($path), file_get_contents($path));
    }

    return $zip->close();
}

$zip = create_zip('/path/to/your/zip/directory', '/path/to/your/save.zip');

header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.basename('/path/to/your/save.zip').'"');
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize('/path/to/your/save.zip'));
echo readfile('/path/to/your/save.zip');

instantate an iterator (before creating the zip archive, just in case the zip file is created inside the source folder) and traverse the directory to get the file list. 实例化一个迭代器(在创建zip归档文件之前,以防zip文件在源文件夹中创建),并遍历目录以获取文件列表。

See More Code At:click me 查看更多代码:点击我

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM