创建一个带密码的zip压缩包

3

因此,我正在创建一个带有密码的 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_location_of_a_file/temp/data/map10/data.txt。所以,我需要从我的文件夹中只留下data.txt而不是其他文件夹。我该怎么办?

3个回答

1
如果有人遇到和我一样的问题,这里是解决方案:只需在shell_execzip后面加上-jrq
shell_exec('zip -jrq -P '.$zipPassword.' '.$zipFileName.'.zip '.$fileName);

之后,完整路径将被忽略。


0
除了@Script47之外...
纯PHP可用于PHP 7.2.0和PECL zip 1.14.0,如果构建针对libzip ≥ 1.2.0。
<?php
$zip = new ZipArchive;
$res = $zip->open('test.zip', ZipArchive::CREATE);
if ($res === TRUE) {
    // Add files
    $zip->addFromString('test.txt', 'file content goes here');
    $zip->addFile('data.txt', 'entryname.txt');

    // Set global (for each file) password
    $zip->setPassword('your_password_here');    

    // This part will set that 'data.txt' will be encrypted with your password
    $zip->setEncryptionName('data.txt', ZipArchive::EM_AES_128);   // Have to encrypt each file in zip

    $zip->close(); 
    echo 'ok';
} else {
    echo 'failed';
}
?>

-1
不如使用ZipArchive类和ZipArchiveOpen::openZipArchive::setPassword函数,而不是使用shell_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。

很抱歉,英语不是我的母语,但您的意思是我只能使用“setPassword”来解密我的zip归档文件,而不能用它来创建和保护我的带密码归档文件吗? - Ilya Spark
为什么建议使用setPassword,如果它只能用于解压缩? - Simone Cabrino
请注意,如上所述,libzip必须是>= 1.2.0。 - Paolo Falomo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接