Php zip archive password

ZipArchive::setPassword

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

User Contributed Notes 3 notes

 $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 .")"); >
$zip = new ZipArchive(); $code = $zip->open('myzip.zip', ZipArchive::CREATE | ZipArchive::OVERWRITE); if ($code === true) echo 'zip opened
'; else echo $code.'
'; $zip->addFile('somefile'); $code = $zip->setPassword('secret'); if ($code === true) echo 'password set
'; else echo $code.'
'; $code = $zip->close(); if ($code === true) echo 'closed
'; else echo $code.'
'; echo 'done
'; 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.
Same problem for me. Unable to passwd protect the zip even though it returns TRUE! Is there any trick to do?

  • ZipArchive
    • addEmptyDir
    • addFile
    • addFromString
    • addGlob
    • addPattern
    • close
    • deleteIndex
    • deleteName
    • extractTo
    • getArchiveComment
    • getCommentIndex
    • getCommentName
    • getExternalAttributesIndex
    • getExternalAttributesName
    • getFromIndex
    • getFromName
    • getNameIndex
    • getStatusString
    • getStream
    • locateName
    • open
    • renameIndex
    • renameName
    • setArchiveComment
    • setCommentIndex
    • setCommentName
    • setExternalAttributesIndex
    • setExternalAttributesName
    • setPassword
    • statIndex
    • statName
    • unchangeAll
    • unchangeArchive
    • unchangeIndex
    • unchangeName

Описание класса ziparchive, примеры использования класса ziparchive.

Источник

ZipArchive::setPassword

Возвращает true в случае успешного выполнения или false в случае возникновения ошибки.

Читайте также:  Habr нейронные сети python

Примечания

Замечание:

Начиная с PHP 7.2.0 и libzip 1.2.0, пароль используется для распаковки архива, а также как пароль по умолчанию для ZipArchive::setEncryptionName() и ZipArchive::setEncryptionIndex() . Ранее эта функция устанавливала пароль только для распаковки. Она не не превращала не защищённый паролем ZipArchive в защищённый ZipArchive .

Смотрите также

  • ZipArchive::setEncryptionIndex() — Установить метод шифрования записи по её индексу
  • ZipArchive::setEncryptionName() — Установить метод шифрования записи по её имени

User Contributed Notes 2 notes

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:

$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 create password protected archive in PHP >= 7.2 use:

$zip -> setEncryptionName ( ‘test.txt’ , ZipArchive :: EM_AES_256 , ‘test’ );
?>

Based on example from the documentation:

$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’ ;
>

  • ZipArchive
    • addEmptyDir
    • addFile
    • addFromString
    • addGlob
    • addPattern
    • clearError
    • close
    • count
    • deleteIndex
    • deleteName
    • extractTo
    • getArchiveComment
    • getArchiveFlag
    • getCommentIndex
    • getCommentName
    • getExternalAttributesIndex
    • getExternalAttributesName
    • getFromIndex
    • getFromName
    • getNameIndex
    • getStatusString
    • getStream
    • getStreamIndex
    • getStreamName
    • isCompressionMethodSupported
    • isEncryptionMethodSupported
    • locateName
    • open
    • registerCancelCallback
    • registerProgressCallback
    • renameIndex
    • renameName
    • replaceFile
    • setArchiveComment
    • setArchiveFlag
    • setCommentIndex
    • setCommentName
    • setCompressionIndex
    • setCompressionName
    • setEncryptionIndex
    • setEncryptionName
    • setExternalAttributesIndex
    • setExternalAttributesName
    • setMtimeIndex
    • setMtimeName
    • setPassword
    • statIndex
    • statName
    • unchangeAll
    • unchangeArchive
    • unchangeIndex
    • unchangeName

    Источник

    githubgobi / zip-files-with-password.md

    You need at least PHP 7.2 to encrypt ZIP files with a password.

     $zip = new ZipArchive(); $zipFile = __DIR__ . '/output.zip'; if (file_exists($zipFile)) < unlink($zipFile); > $zipStatus = $zip->open($zipFile, ZipArchive::CREATE); if ($zipStatus !== true) < throw new RuntimeException(sprintf('Failed to create zip archive. (Status code: %s)', $zipStatus)); > $password = 'top-secret'; if (!$zip->setPassword($password)) < throw new RuntimeException('Set password failed'); > // compress file $fileName = __DIR__ . '/test.pdf'; $baseName = basename($fileName); if (!$zip->addFile($fileName, $baseName)) < throw new RuntimeException(sprintf('Add file failed: %s', $fileName)); > // encrypt the file with AES-256 if (!$zip->setEncryptionName($baseName, ZipArchive::EM_AES_256)) < throw new RuntimeException(sprintf('Set encryption failed: %s', $baseName)); > $zip->close();

    Источник

    ZipArchive::setEncryptionName

    Установить метод шифрования записи, указанной по её имени.

    Список параметров

    Метод шифрования, заданный одной из констант ZipArchive::EM_.

    Пароль. Если не указывать, то будет использован пароль по умолчанию.

    Возвращаемые значения

    Возвращает true в случае успешного выполнения или false в случае возникновения ошибки.

    Список изменений

    Примеры

    В этом примере создаётся ZIP-архив test.zip , содержащий файл test.txt , зашифрованный с помощью AES 256.

    Пример #1 Архивируем и шифруем файл

    $zip = new ZipArchive ();
    if ( $zip -> open ( ‘test.zip’ , ZipArchive :: CREATE ) === TRUE ) $zip -> setPassword ( ‘secret’ );
    $zip -> addFile ( ‘text.txt’ );
    $zip -> setEncryptionName ( ‘text.txt’ , ZipArchive :: EM_AES_256 );
    $zip -> close ();
    echo «готово\n» ;
    > else echo «ошибка\n» ;
    >
    ?>

    Примечания

    Замечание:

    Функция доступна только если скомпилировано с использованием libzip ≥ 1.2.0.

    Смотрите также

    • ZipArchive::setPassword() — Установка пароля для активного архива
    • ZipArchive::setEncryptionIndex() — Установить метод шифрования записи по её индексу

    User Contributed Notes 2 notes

    Files compressed using this function on Linux won’t be decompressed using Windows.

    There seems to be some incompatibility with Windows built-in decompressor.

    There’s an alternative library that works better here: https://github.com/Ne-Lexa/php-zip

    I got windows to open a file created with it by using the PKWARE encryption method

    On windows is the «EM_AES_256» by default not supported, but you can use winrar, winzip or 7zip.

    At first we had a password of 128 chars (this was to long) and all extract applications give an error that the password was incorrect.

    The next time we did use a password of 52 chars., this time i did work!

    • ZipArchive
      • addEmptyDir
      • addFile
      • addFromString
      • addGlob
      • addPattern
      • clearError
      • close
      • count
      • deleteIndex
      • deleteName
      • extractTo
      • getArchiveComment
      • getArchiveFlag
      • getCommentIndex
      • getCommentName
      • getExternalAttributesIndex
      • getExternalAttributesName
      • getFromIndex
      • getFromName
      • getNameIndex
      • getStatusString
      • getStream
      • getStreamIndex
      • getStreamName
      • isCompressionMethodSupported
      • isEncryptionMethodSupported
      • locateName
      • open
      • registerCancelCallback
      • registerProgressCallback
      • renameIndex
      • renameName
      • replaceFile
      • setArchiveComment
      • setArchiveFlag
      • setCommentIndex
      • setCommentName
      • setCompressionIndex
      • setCompressionName
      • setEncryptionIndex
      • setEncryptionName
      • setExternalAttributesIndex
      • setExternalAttributesName
      • setMtimeIndex
      • setMtimeName
      • setPassword
      • statIndex
      • statName
      • unchangeAll
      • unchangeArchive
      • unchangeIndex
      • unchangeName

      Источник

      Create ZIP file with password – PHP

      To create a ZIP file with password in PHP, there isn’t any need for third-party library. PHP provides a large variety of built-in functions to create a ZIP file. Also PHP has an in-built option for setting the password on ZIP files.

      We will creating a simple script to allow user to upload multiple files, then will compress those files in ZIP and asking the password from user. And apply that password on that ZIP file.

      We will be creating just 2 files, 1 for client (index.php) and 1 for server (upload.php). So, start off by creating a simple HTML form in file index.php:

      Create form to select multiple files (index.php)

      enctype=”multipart/form-data” and method=”POST” are important in tag to upload file.

      multiple attribute will be used to allow user to select multiple files.

      Upload, compress files to ZIP (upload.php)

      Creates a built-in ZipArchive class object and save it in variabled called $zip.

      Call open() function from $zip object to create a new empty ZIP file in memory.

      $zip->open("file.zip", ZIPARCHIVE::CREATE);
      • First parameter is the name of ZIP file you want to set.
      • Second is the action you want to perform, you can use OPEN, CREATE methods to read or write the file respectively.

      As we are allowing user to select multiple files, we need to create a loop on user selected files:

      Inside this loop, we have to get the content of each file separately:

      $content = file_get_contents($_FILES["files"]["tmp_name"][$a]);

      Then you have to call the addFromString() method on $zip object. It accepts 2 parameters, 1st is the name of file inside the ZIP archive, 2nd is the content of file. In this case, 2nd parameter is stored in variable called $content.

      $zip->addFromString($_FILES["files"]["name"][$a], $content);

      After the loop, we have to call the close() to free-up the space in memory.

      At this point, your index.php file will look like this:

      And your upload.php file will look like this:

      open("file.zip", ZIPARCHIVE::CREATE); for ($a = 0; $a < count($_FILES["files"]["name"]); $a++) < $content = file_get_contents($_FILES["files"]["tmp_name"][$a]); $zip->addFromString($_FILES["files"]["name"][$a], $content); > $zip->close(); ?>

      Applying password to archive (upload.php)

      Create simple password input field in index.php file:

      And in upload.php file, after the open() method, call the setPassword() method and send user selected password as parameter:

      $zip->setPassword($_POST["password"]);

      And in loop, after addFromString() method, call setEncryptionName() method to apply password on each file in the ZIP:

      $zip->setEncryptionName($_FILES["files"]["name"][$a], ZipArchive::EM_AES_256);
      • 1st parameter is the name of file.
      • 2nd parameter is the type of encryption algorithm used.

      Below is the complete source code of both files:

      index.php

      upload.php

      open("file.zip", ZIPARCHIVE::CREATE); $zip->setPassword($_POST["password"]); for ($a = 0; $a < count($_FILES["files"]["name"]); $a++) < $content = file_get_contents($_FILES["files"]["tmp_name"][$a]); $zip->addFromString($_FILES["files"]["name"][$a], $content); $zip->setEncryptionName($_FILES["files"]["name"][$a], ZipArchive::EM_AES_256); > $zip->close(); ?>

      Run the index.php file, upload some files and set the password. Your selected files will be archived to 1 and password will be applied.

      If you want to ZIP your files and protect them with password in command line, follow here.

      Right now, this only works for Mac OS X.

      Источник

Оцените статью