Php 使用密码创建zip存档
因此,我创建了一个带有密码的zip文件:Php 使用密码创建zip存档,php,zip,Php,Zip,因此,我创建了一个带有密码的zip文件: function createZip($fileName,$fileText,$zipFileName,$zipPassword) { shell_exec('zip -P '.$zipPassword.' '.$zipFileName.'.zip '.$fileName); unlink($fileName); return file_exists($zipFileName.'.zip');
function createZip($fileName,$fileText,$zipFileName,$zipPassword)
{
shell_exec('zip -P '.$zipPassword.' '.$zipFileName.'.zip '.$fileName);
unlink($fileName);
return file_exists($zipFileName.'.zip');
}
$filex = "/backup/home/fyewhzjp/long_location_of_a_file/temp/data/map10/data.txt";
// $file_content = 'test';
$archive = "/backup/home/fyewhzjp/long_location_of_a_file/temp/data/map10/archive";
createZip($filex,$file_content,$archive,$pass);
它是有效的。我在网站上的/temp/data/map
文件夹中得到了一个archive.zip
。但是,当我打开我的归档文件时,我可以看到一堆文件夹,最后是data.txt,假设是这样的
/backup/home/fyewhzjp/long\u位置\u文件/temp/data/map10/data.txt
因此,我只需要在我的文件夹中保留
data.txt
,而不需要其他文件夹。我该怎么做呢?与其使用shell\u exec
不如将类与函数一起使用,这样似乎会让事情变得更简单
<?php
$zip = new ZipArchive;
$res = $zip->open('test.zip', ZipArchive::CREATE);
if ($res === TRUE) {
$zip->addFromString('test.txt', 'file content goes here');
$zip->addFile('data.txt', 'entryname.txt');
$zip->setPassword('your_password_here');
$zip->close();
echo 'ok';
} else {
echo 'failed';
}
?>
注:
此功能仅设置用于解压缩存档文件的密码;它不会将不受密码保护的ZipArchive转换为受密码保护的ZipArchive
如果有人会面临与我相同的问题,以下是解决方案: 只需在
shell_exec
中的zip
之后添加-jrq
,如下所示:
shell_exec('zip -jrq -P '.$zipPassword.' '.$zipFileName.'.zip '.$fileName);
之后,将忽略完整路径。除了@Script47 纯PHP分别从PHP7.2.0和PECL zip 1.14.0开始提供,如果是基于libzip构建的≥ 1.2.0
很抱歉,英语不是我的母语,但您的意思是我只能使用“setPassword”来解密我的zip存档,而不是使用密码创建和保护我的存档?如果setPassword可以用于解压缩,为什么建议使用它?请注意,如上所述,libzip必须>=1.2.0