update page now
Laravel Live Japan

ZipArchive::setPassword

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

ZipArchive::setPasswordアクティブなアーカイブにパスワードを設定する

説明

public ZipArchive::setPassword(#[\SensitiveParameter] string $password): bool

アクティブなアーカイブにパスワードを設定します。

パラメータ

password

アーカイブに使用されるパスワード。

戻り値

成功した場合に true を、失敗した場合に false を返します。

注意

注意:

PHP 7.2.0 と libzip 1.2.0 以降では、パスワードはアーカイブを解凍するのに使われます。 そして、ZipArchive::setEncryptionName()ZipArchive::setEncryptionIndex() のデフォルトのパスワードとしても使われます。 これより前のバージョンでは、この関数はアーカイブの解凍のみに使うパスワードを設定していました。 つまり、パスワードで保護されていない ZipArchive をパスワードで保護された ZipArchive に変換していませんでした。

参考

add a note

User Contributed Notes 2 notes

up
18
stanislav dot eckert at vizson dot de
11 years 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
1
blindfury at mailinator dot com
7 years ago
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';
}

?>
To Top