代码之家  ›  专栏  ›  技术社区  ›  Ilya Spark

使用密码创建zip存档

  •  3
  • Ilya Spark  · 技术社区  · 8 年前

    因此,我创建了一个带有密码的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);
    

    archive.zip 在我的 /temp/data/map /backup/home/fyewhzjp/long_location_of_a_file/temp/data/map10/data.txt data.txt 在我的文件夹中,没有其他文件夹。我该怎么做?

    3 回复  |  直到 8 年前
        1
  •  1
  •   Ilya Spark    8 年前

    只需添加 -jrq 之后 zip shell_exec 这样地:

    shell_exec('zip -jrq -P '.$zipPassword.' '.$zipFileName.'.zip '.$fileName);
    

    之后,将忽略完整路径。

        2
  •  0
  •   Tonoslav    6 年前

    除了@Script47。。。

    纯PHP从开始提供 PHP 7.2.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';
    }
    ?>
    
        3
  •  -1
  •   Script47    8 年前

    而不是使用 shell_exec 你为什么不直接使用 ZipArchive ZipArchiveOpen::open ZipArchive::setPassword ,似乎这会让事情变得容易得多。

    <?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。