• 首页
  • vue
  • TypeScript
  • JavaScript
  • scss
  • css3
  • html5
  • php
  • MySQL
  • redis
  • jQuery
  • ZipArchive::setPassword()

    (PHP 5 >= 5.6.0, PHP 7, PECL zip >= 1.12.4)

    Set the password for the active archive

    说明

    publicZipArchive::setPassword(string $password): bool

    Sets the password for the active archive.

    参数

    $password

    The password to be used for the archive.

    返回值

    成功时返回TRUE,或者在失败时返回FALSE

    注释

    Note:

    As of PHP 7.2.0 and libzip 1.2.0 the password is used to decompress the archive, and is also the default password for ZipArchive::setEncryptionName() and ZipArchive::setEncryptionIndex(). Formerly, this function only set the password to be used to decompress the archive; it did not turn a non-password-protected ZipArchive into a password-protected ZipArchive.

    参见

    • ZipArchive::setEncryptionIndex() Set the encryption method of an entry defined by its index
    • ZipArchive::setEncryptionName() Set the encryption method of an entry defined by its name
    It seems that this function supports only decryption of password protected archives (see changelog: http://pecl.php.net/package-changelog.php?package=zip). Creation of password protected archives is not supported (they will be created simply as non-protected archives).
    Example code for extraction of files from password protected ZIP archives:
    <?php
      $zip = new ZipArchive();
      $zip_status = $zip->open("test.zip");
      if ($zip_status === true)
      {
        if ($zip->setPassword("MySecretPassword"))
        {
          if (!$zip->extractTo(__DIR__))
            echo "Extraction failed (wrong password?)";
        }
        $zip->close();
      }
      else
      {
        die("Failed opening archive: ". @$zip->getStatusString() . " (code: ". $zip_status .")");
      }
    ?>
    
    To create password protected archive in PHP >= 7.2 use:
    <?php
      $zip->setEncryptionName('test.txt', ZipArchive::EM_AES_256, 'test');
    ?>
    Based on example from the documentation:
    <?php
    $zip = new ZipArchive;
    $res = $zip->open('test.zip', ZipArchive::CREATE);
    if ($res === TRUE) {
      $zip->addFromString('test.txt', 'file content goes here');
      $zip->setEncryptionName('test.txt', ZipArchive::EM_AES_256, 'passw0rd');
      $zip->close();
      echo 'ok';
    } else {
      echo 'failed';
    }
    ?>