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 add to the archive.

Return Values

Returns TRUE on success or FALSE on failure.

add a note add a note

User Contributed Notes 2 notes

up
1
stanislav dot eckert at vizson dot de
29 days 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 .")");
    }
?>
up
0
@mikeziri
1 month 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.
To Top