ZipArchive::setPassword

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

ZipArchive::setPasswordSet the password for the active archive

Description

public bool ZipArchive::setPassword ( string $password )

Sets the password for the active archive.

Parameters

password

The password to be used for the archive.

Return Values

Returns TRUE on success or FALSE on failure.

Notes

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.

add a note add a note

User Contributed Notes 4 notes

up
4
Erutan409 at Hotmail dot com
3 months ago
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.
up
2
@mikeziri
10 months ago
$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.
up
0
carlmcdade at gmail dot com
4 months ago
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.
up
0
stanislav dot eckert at vizson dot de
10 months ago
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 Top