文字

ZipArchive::setPassword

(PHP 5 >= 5.6.0, 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.

用户评论:

[#1] Erutan409 at Hotmail dot com [2015-04-13 13:14:44]

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.

[#2] carlmcdade at gmail dot com [2015-03-10 11:44:35]

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.

[#3] stanislav dot eckert at vizson dot de [2014-09-26 02:43:23]

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 .")");
    }
?>

[#4] @mikeziri [2014-09-18 00:37:56]

$zip = new ZipArchive();
$code = $zip->open('myzip.zip', ZipArchive::CREATE | ZipArchive::OVERWRITE);
if ($code === true)
echo 'zip opened<br>';
else
echo $code.'<br>';
$zip->addFile('somefile');

$code = $zip->setPassword('secret');

if ($code === true)
echo 'password set<br>';
else
echo $code.'<br>';

$code = $zip->close();
if ($code === true)
echo 'closed<br>';
else
echo $code.'<br>';

echo 'done<br>';

this prints:

zip opened
password set
closed
done

on the filesystem, the myzip.zip is created with somefile inside but the zip file is not password protected.

上一篇: 下一篇: