【发布时间】:2021-04-08 05:24:22
【问题描述】:
我正在使用以下函数来创建我的 MySQL 数据库的备份。这确实很好用,它会生成一个包含所有内容的.sql 文件。该文件本身最近大约有 36 兆字节。我希望将文件压缩成 zip 以帮助节省一些磁盘空间。我可以创建.zip,它似乎可以工作并创建大约4.5 MB 的.zip 文件。但是,我尝试下载 zip 文件并在 Windows 10 上打开它,我得到了:
此文件夹为空。
当我尝试解压 zip 时,即使它是空的,我也会得到:
Windows 无法完成提取。
压缩(压缩)文件夹 {filepath} 无效。
我使用了echo 'The zip archive contains ',$zip->numFiles,' files with a status of ',$zip->status;,它给了我:
zip 存档包含 1 个状态为 0 的文件
使用 ZipArchive 打开 zipfile 并 var 转储结果给了我:
object(ZipArchive)[15]
public 'status' => int 0
public 'statusSys' => int 0
public 'numFiles' => int 1
public 'filename' => string '/backups/mysql/2021-01-01-0258-mysql_backup_1609491536.zip' (length=91)
public 'comment' => string '' (length=0)
我在做什么会损坏我无法解压缩或在 Windows 上查看文件的文件? PHP 似乎能够告诉文件在那里。
function backup_tables($savepath,$tables = '*',$zip=true) {
$savepath = rtrim($savepath,'/');
$filepath = $savepath.'/';
$name = date("Y-m-d-hi").'-mysql_backup_'.time();
$fileName = $filepath.$name.'.sql';
$zipName = $filepath.$name.'.zip';
//$this->select("SET NAMES 'utf8'");
exec('mysqldump --user='.escapeshellarg($this->user).' --password='.escapeshellarg($this->pass).' --host='.escapeshellarg($this->host).' '.escapeshellarg($this->db).' > '.escapeshellarg($fileName).'');
if(file_exists($fileName)) {
//if(fclose($handle)){
if($zip==true) {
$zip = new ZipArchive();
if($zip->open($zipName,ZIPARCHIVE::CREATE) !== true) {
return false;
}
//add the files
$zip->addFile($fileName);
//debug
//echo 'The zip archive contains ',$zip->numFiles,' files with a status of ',$zip->status;
//close the zip -- done!
$zip->close();
if(file_exists($zipName)) {
//unlink($fileName);
}
$za = new ZipArchive();
$za->open($zipName);
var_dump($za);
/* All good for Zip but return nothing. */
return true;
}
else {
/* All good for .sql file but return nothing. */
return true;
}
exit;
}
else {
echo 'SQL file does not exists at: '.$fileName;
}
}
更新
正如答案中所指出的,我打开文件时变量名错误。我现在在var_dump($za) 上得到这个。
object(ZipArchive)[15]
public 'status' => int 0
public 'statusSys' => int 0
public 'numFiles' => int 1
public 'filename' => string '.../backups/mysql/2021-01-01-0313-mysql_backup_1609492418.zip' (length=91)
public 'comment' => string '' (length=0)
它现在说里面只有一个文件;但是它在 Windows 上仍然损坏。
【问题讨论】:
标签: php windows-10 zip unzip ziparchive