ZipArchive::setPassword

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

ZipArchive::setPasswordSet the password for the active archive

说明

public bool ZipArchive::setPassword ( string $password )

Sets the password for the active archive.

参数

password

The password to be used for the archive.

返回值

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

注释

Note:

This function only sets the password to be used to decompress the archive; it does not turn a non-password-protected ZipArchive into a password-protected ZipArchive.

User Contributed Notes

Erutan409 at Hotmail dot com 13-Apr-2015 10:14
Wouldn't it make sense for this method to be named ZipArchive::usePassword, instead?  There seems to be a lot of people thinking that its name, currently (ZipArchive::setPassword), is for applying a password.  I think nomenclature should certainly be up for discussion on this method.
carlmcdade at gmail dot com 10-Mar-2015 08:44
As noted earlier  the  method does not actually set a  password. It enters the password to allow decryption of the archive for reading.

It  does not:

1) create an encrypted archive
2) allow the addition of encrypted files to the archive
3) read  AES256 encryption/compression
4) throw catchable errors use $zip->getStatusString()

Hopefully someone will get around to fixing the doc to reflect all of this.
stanislav dot eckert at vizson dot de 26-Sep-2014 11:43
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 .")");
    }
?>