首页 > 解决方案 > 将 ZipArchive 与 PHP 8 和临时文件一起使用

问题描述

PHP 8 改变了 ZIP 存档的“打开”方式,并指出:

不推荐使用空文件作为 ZipArchive。Libzip 1.6.0 不再接受空文件作为有效的 zip 存档。

在下面的测试代码中,打开名为 ZIP 文件的文件$backupzip没有错误,但打开 ZIP 文件名$invoicezip失败并出现错误:

不推荐使用:ZipArchive::open():在第 12 行不推荐使用空文件作为 ZipArchive

<?php
declare(strict_types=1);
ini_set('display_errors','1');ini_set('display_startup_errors','1');error_reporting(E_ALL);
    
define('BACKUPDIR','E:\Database_Backups\\');
$backupfile = BACKUPDIR . date('Ymd') . '.zip';
$temp_file  = tempnam(sys_get_temp_dir(),'AW');

$backupzip  = new ZipArchive();
$invoicezip = new ZipArchive();

$backupzip->open($backupfile,ZipArchive::CREATE);  // <<<--- this works
$invoicezip->open($temp_file,ZipArchive::CREATE);  // <<<--- this fails

标签: phpziparchivephp-8

解决方案


失败的原因是tempnam函数的使用实际上创建了一个零字节文件,这ZipArchive::CREATE就是抱怨的原因。

解决方案是在尝试使用它之前unlink创建的临时文件。tempnam在问题的示例中,我只是unlink($temp_file);$temp_file = tempnam(sys_get_temp_dir(),'AW');.

前几行现在看起来像这样:

<?php
declare(strict_types=1);
ini_set('display_errors','1');ini_set('display_startup_errors','1');error_reporting(E_ALL);
    
define('BACKUPDIR','E:\Database_Backups\\');
$backupfile = BACKUPDIR . date('Ymd') . '.zip';
$temp_file  = tempnam(sys_get_temp_dir(),'AW');
unlink($temp_file);

推荐阅读