php - 将 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
解决方案
失败的原因是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);
推荐阅读
- virtualenv - 全局运行虚拟环境?
- reactjs - 如何在 IE 中显示 React 应用程序?当它在所有其他浏览器本地主机和生产中正常工作时?
- facebook-messenger - 如何使按钮在信使聊天机器人上工作?
- python - neo4j 更改对象中的视觉设置
- javascript - IIFE 内部 for 循环错误 VM531:3 Uncaught TypeError: console.log(...)
- google-cloud-stackdriver - 如何检索 GCP Stackdriver 人类可读日志?
- wordpress - 图片上的弹出文字点击WordPress
- php - php google analytics api如何获取用户访问的帖子的日期和时间
- c - 如何制作#define函数的for循环?
- visual-studio - Unity 项目,Visual Studio 2019 包含的文件在重新打开时消失