Creating a Password Protected Zip File using PHP in Windows

限于喜欢 提交于 2019-12-24 00:52:50

问题


I am creating a zip file of a given file in PHP. Following is the function

function create_zip($file, $file_name) 
{   
    $zip = new ZipArchive();
    $zip_name = $file_name. ".zip"; // Zip name
    $zip->open($zip_name,  ZipArchive::CREATE);

    if (file_exists($file)) {
        $zip->addFromString(basename($file),  file_get_contents($file));
    } else {
        return "file does not exist";
    }
    $zip->close();

    return $zip_name;   
}

I want to add password protection for the Zip files. I have found following code to create a password protected zip file

system('zip -P password file.zip file.txt');  

But it is not working properly. Can you please Guide me How can I add the Password protection on the Zip file?


回答1:


PHP Zip - http://php.net/manual/en/book.zip.php - doesn't support password protected zip files, you will need do it via command line.

To password protect a file, you need to use zip command line, make sure that the zip command line program is present, it is not installed by default on many systems.




回答2:


In new PHP 5.6 (currently in beta) you can use your ZipArchive to create password protected archives. All you need is to add this code ZipArchive::setPassword($password)

Edit: Apparently it only supports decryption, not encryption yet.




回答3:


I realize this is an old thread, but anyone struggling with adding a password to an archive in windows environment, I solved this using winrar command line and exec in PHP.

Download winrar from http://www.rarlab.com/ and include the WinRAR.exe in your PHP script directory, or call it from the right directory in your exec command.

exec("winrar a -p[password] [archive name] [file or folders to include]");

winrar in the above example refers to winrar.exe in the same directory as your script. If winrar.exe is NOT in the same directory as your script, you can simply include the path:

exec("C:\Program Files\Winrar...

So, for example: exec("winrar a -ppassword archive.zip file.txt");

Will result in an archive named "archive.zip" being created with "file.txt" inside, and a password of "password".

For more information on winrar command line: http://acritum.com/software/manuals/winrar/



来源:https://stackoverflow.com/questions/20883532/creating-a-password-protected-zip-file-using-php-in-windows

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!