2

As a part of my web application I want to upload file.
I want to protect his files with a Password.
What I want to do is to take the uploaded file, zip it, and give the .zip file a password.
I know How to upload a file in laravel but I don't know how to zip it and set password.
I'm using the below code to upload file.

$mobimg=$request->file('img'); 
$newfile2 = rand(456,987).time().$mobimg->getClientOriginalName();
 $mobimg->move('images/upload', $newfile2);

 $data=array(                      
               'img' => $newfile2,

               );
               DB::table('file_upload')->insert($data);

I hope someone will help me do this
Thanks in advance.

Touheed Khan
  • 2,149
  • 16
  • 26
palika
  • 41
  • 2
  • 10
  • Using PHP to generate a password protected ZIP is generally insecure, unless you are using PHP 7.2. Please see https://stackoverflow.com/a/646221/823549 for more details. – 1000Nettles Feb 18 '18 at 18:05

1 Answers1

1

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();
odan
  • 4,757
  • 5
  • 20
  • 49