Create a zip archive with a password

Viewed 3064

So, I creating a zip file with a password:

function createZip($fileName,$fileText,$zipFileName,$zipPassword)
    {

       shell_exec('zip -P '.$zipPassword.' '.$zipFileName.'.zip '.$fileName);
       unlink($fileName);
       return file_exists($zipFileName.'.zip');
    }


    $filex = "/backup/home/fyewhzjp/long_location_of_a_file/temp/data/map10/data.txt";
    // $file_content = 'test';
    $archive = "/backup/home/fyewhzjp/long_location_of_a_file/temp/data/map10/archive";

    createZip($filex,$file_content,$archive,$pass);

And it works. I'm getting a archive.zip in my /temp/data/map folder on the website. But, when I open my archive I can see a bunch of folders, and data.txt at the end, let's say it will be /backup/home/fyewhzjp/long_location_of_a_file/temp/data/map10/data.txt So, I need to leave only data.txt in my folder, without other folders. How can I do it?

3 Answers

If anyone will face the same problem as I did, here is the solution: Just add -jrq after zip in shell_exec like this:

shell_exec('zip -jrq -P '.$zipPassword.' '.$zipFileName.'.zip '.$fileName);

After that, full path will be ignored.

In addition to @Script47...

Pure PHP Available as of PHP 7.2.0 and PECL zip 1.14.0, respectively, if built against libzip ≥ 1.2.0.

<?php
$zip = new ZipArchive;
$res = $zip->open('test.zip', ZipArchive::CREATE);
if ($res === TRUE) {
    // Add files
    $zip->addFromString('test.txt', 'file content goes here');
    $zip->addFile('data.txt', 'entryname.txt');

    // Set global (for each file) password
    $zip->setPassword('your_password_here');    

    // This part will set that 'data.txt' will be encrypted with your password
    $zip->setEncryptionName('data.txt', ZipArchive::EM_AES_128);   // Have to encrypt each file in zip

    $zip->close(); 
    echo 'ok';
} else {
    echo 'failed';
}
?>

Rather than using shell_exec why don't you just use the ZipArchive class with the functions ZipArchiveOpen::open and ZipArchive::setPassword, it seems that that would make things a lot easier.

<?php
$zip = new ZipArchive;
$res = $zip->open('test.zip', ZipArchive::CREATE);
if ($res === TRUE) {
    $zip->addFromString('test.txt', 'file content goes here');
    $zip->addFile('data.txt', 'entryname.txt');
    $zip->setPassword('your_password_here');
    $zip->close(); 
    echo 'ok';
} else {
    echo 'failed';
}
?>

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.

Related