How to excel password protected in zip file in php - php

I want to download excel in zip folder. After that, it should be password protected. But it does not work.
public function download (){
$header = array('id');
require_once APPPATH."/third_party/PHPExcel.php";
$sheet = new PHPExcel();
$file = $this->appmodel->Data();
// echo "<pre>"; print_r($file); die;
$filename = $file->id;
$this->load->helper('date');
$date = date('Y-m-d');
//1st Sheet
$sheet->setActiveSheetIndex(0);
$activeSheet = $sheet->getActiveSheet();
$activeSheet->fromArray($header, null);
$objWriter = PHPExcel_IOFactory::createWriter($sheet, 'Excel2007');
// echo "<pre>"; print_r($objWriter); die;
$excel_file_tmp = tempnam("/tmp", 'your_prefix');
$objWriter->save($excel_file_tmp);
//zip
$zip_file_tmp = tempnam("/tmp", 'your_prefix');
$zip = new ZipArchive();
$zip->open($zip_file_tmp, ZipArchive::OVERWRITE);
$zip->addFile($excel_file_tmp, 'your_name.xlsx');
$zip->close();
//download
$password = "22";
$download_filename = 'your_name.zip';
header("Content-Type: application/octet-stream");
header("Content-Length: " . filesize($zip_file_tmp));
header("Content-Disposition: attachment; filename=\"" . $download_filename . "\"");
#system("zip -P $password $excel_file_tmp $zip_file_tmp ");
readfile($zip_file_tmp);
// unlink($excel_file_tmp);
// unlink($zip_file_tmp);
#unlink($zip_file_tmp);
}

Since PHP >7.2 you can use setEncryptionName to procted a ZIP archive with a password.
if ($res === TRUE) {
$zip->addFromString('FILENAME_WITH_EXTENSION', 'file content goes here'); //Add your file name
$zip->setEncryptionName('FILENAME_WITH_EXTENSION', ZipArchive::EM_AES_256, 'PASSWORD'); //Add file name and password dynamically
$zip->close();
echo 'ok';
} else {
echo 'failed';
}
See more at Protect ZIP Archive with password

Related

get empty file after download

i want to download a file of projet but i get it empty. i'am using a spreadsheet librairy
Notice : i a make a dump after save function , my file is full and not empty in the path directory of project
Someone can help me !
bellow is my code :
$spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load('template.xlsx');
$worksheet = $spreadsheet->getActiveSheet();
$filename = 'write.xls';
$worksheet->getCell('A1')->setValue('John');
$worksheet->getCell('A2')->setValue('Smith');
$writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xls');
$writer->save($filename); die;
// to download file
header('Content-Type: application/vnd.ms-excel');
header("Content-Length:".filesize($filename));
header("Content-Disposition: attachment;filename=$filename");
header('Cache-Control: max-age=0');
$writer->save('php://output');
exit();
i except a full file after downloading it
This function would work:
define ("ONE_DAY", 86400);
function getExisting()
{
$rootFolder = "pathTodirectory";
//first clear old files
$files = scandir($rootFolder,1);
array_pop($files); array_pop($files);
foreach($files as $file)
{
$fp = $rootFolder . DIRECTORY_SEPARATOR . $file;
$filemtime=filemtime($fp);
if (time() - $filemtime >= (2 * ONE_DAY))unlink($fp);
}//end clearing old files
//second rescan folder for current files
$files = scandir($rootFolder,1);
array_pop($files); array_pop($files);
$existing = array_reverse($files);
return $existing;
}
$existing = getExisting();
echo "\n<p> Select file or enter office number to review inventory:";
echo "\n <ul>";
foreach($existing as $rpt)
{
$spd = "pathTodirectory" . $rpt; \\make sure to follow up with relative path name here also
echo "\n <li><a href=\"$spd\" >" . $rpt ."</a></li>";
}
echo "\n </ul>";
I think it is the load() usage issue, your code works with following correction in my site :
$file_loc = 'template.xlsx';
$file_type = \PhpOffice\PhpSpreadsheet\IOFactory::identify($file_loc);
$reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader($file_type);
// $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load('template.xlsx');
$spreadsheet = $reader->load($file_loc);
$worksheet = $spreadsheet->getActiveSheet();
$filename = 'write.xls';
$worksheet->getCell('A1')->setValue('John');
$worksheet->getCell('A2')->setValue('Smith');
$writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xls');
// save a physical file in server, you can skip this actually
$writer->save($target_dir . $filename);
// die; // don't die, be happy (^_^)
// to download file
header('Content-Type: application/vnd.ms-excel');
header("Content-Length:" . filesize($filename));
header("Content-Disposition: attachment;filename=$filename");
header('Cache-Control: max-age=0');
$writer->save('php://output');
exit();

How to create a zip file with PDF files with the addFromString function in php?

I have this code broken down into two parts:
The first one create me a zip file empty and download it.
The second one download me from my database a PDF file that I decoded in base64.
Both work well separately. I would like to be able to merge them and download in zip format two PDF files that are in my database.
I would like to use the addFromString function to not create a folder on my server but to download the zip file directly for the user.
Can you help me please?
Thanks for your help
<?php
include '../include/classe_PDO.php';
$suivi = $_POST['suivi'];
// //ZIP PART
//Name zip folder with date
$dirzip = date('Ymd His')."_andromeda";
// Zip creation
$nomzip = "C:/wamp64/www\Dylan/SAV/final/include/$dirzip.zip";
$zip = new ZipArchive;
if($zip -> open($nomzip, ZipArchive::CREATE ) === TRUE)
{
$dir = opendir($chemin);
while($fichier = readdir($dir))
{
if(is_file($chemin.$fichier))
{
$zip -> addFromString($file, $decoded);
}
}
$zip ->close();
}
//Zip download
header('Content-Type: application/zip');
header('Content-Disposition: attachment; filename="'.basename($nomzip).'"');
header('Content-Length: ' . filesize($nomzip));
flush();
readfile($nomzip);
//DOWNLOAD PART
try {
// Connect to db
$db = new db('mysql:dbname=jotform; host=localhost', 'root', '');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Set SQL
$sql = "SELECT * FROM `dhl` WHERE `submission_id` = :suivi";
// Prepare query
$query = $db->prepare($sql);
// Execute query
$query->execute(array(':suivi' => $suivi));
foreach ($query as $row) {
$filedata = $row['label_envoi']; //get base64 data from query result
$decoded = base64_decode($filedata); //decode base64 to binary
$filedata2 = $row['label_retour']; //Second column
$decoded2 = base64_decode($filedata2);
//set suitable HTTP response headers
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="label.pdf"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
//output the binary file data in the body of the response
echo $decoded;
}
} catch (PDOException $e) {
echo 'Error: ' . $e->getMessage();
}
?>
You need to loop through your database rows and add each piece of decoded file data to the zip file. Then download the zip at the end.
For example:
include '../include/classe_PDO.php';
$suivi = $_POST['suivi'];
// //ZIP PART
//Name zip folder with date
$dirzip = date('Ymd His')."_andromeda";
// Zip creation
$nomzip = "C:/wamp64/www/Dylan/SAV/final/include/$dirzip.zip";
$zip = new ZipArchive;
if ($zip->open($nomzip, ZipArchive::CREATE ) === TRUE)
{
try {
//connect to DB
$db = new db('mysql:dbname=jotform; host=localhost', 'root', '');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//prepare and execute query
$sql = "SELECT * FROM `dhl` WHERE `submission_id` = :suivi";
$query = $db->prepare($sql);
$query->execute(array(':suivi' => $suivi));
foreach ($query as $row) {
//decode base64 to binary
$decoded = base64_decode($row['label_envoi']);
$decoded2 = base64_decode($row['label_retour']);
//add to zip
//N.B. if there could be more than one row returned by the database, you'll need to ensure the PDFs have unique names instead of these hard-coded ones
$zip->addFromString("label1.pdf", $decoded);
$zip->addFromString("label2.pdf", $decoded2);
}
}
catch (PDOException $e) {
echo 'Error: ' . $e->getMessage();
}
$zip ->close();
//Zip download
header('Content-Type: application/zip');
header('Content-Disposition: attachment; filename="'.basename($nomzip).'"');
header('Content-Length: ' . filesize($nomzip));
flush();
readfile($nomzip);
}
else
{
echo "Error - Zip file could not be created";
}

Download Zip file in php

I want to download my zip file by a variable ($direccion) that I want to assign to it and when I try to do it, it comes out that the file is corrupted.
$file_name = basename('C:/xampp/htdocs/issv/upload/26908557.zip');
header("Content-Type: application/Zip");
header("Content-Disposition: attachment; filename=26908557.zip");
header("Content-Length: " . filesize('C:/xampp/htdocs/issv/upload/26908557.zip'));
readfile('C:/xampp/htdocs/issv/upload/26908557.zip');
exit;
that's my code and it only works that way, but I want to put the $direccion path to it
$direccion='c:/xampp/htdocs/issv/upload/'.trim($cedula);
this is what my variable $cédula means $cedula=$_POST['cedula'];
There many ways of zip file creation which are;
$zip_file = '(path)/filename.zip';$dir = plugin_dir_path( __FILE__ );
$zip_file = $dir . '/filename.zip';$zip = new ZipArchive();
if ( $zip->open($zip_file, ZipArchive::CREATE) !== TRUE) {
exit("message");
} $zip->addFile('full_path_of_the_file', 'custom_file_name); $download_file = file_get_contents( $file_url );
$zip->addFromString(basename($file_url),$download_file); $zip->close();
Or simply do this:
$url = "http://anysite.com/file.zip";$zip_file = "folder/downloadfile.zip";$zip_resource = fopen($zipFile, "w");$ch_start = curl_init();curl_setopt($ch_start, CURLOPT_URL, $url);curl_setopt($ch_start,CURLOPT_FAILONERROR, true);curl_setopt($ch_start,CURLOPT_HEADER, 0);curl_setopt($ch_start,CURLOPT_FOLLOWLOCATION, true);curl_setopt($ch_start,CURLOPT_AUTOREFERER, true);curl_setopt($ch_start,CURLOPT_BINARYTRANSFER,true);curl_setopt($ch_start,CURLOPT_TIMEOUT, 10);curl_setopt($ch_start,CURLOPT_SSL_VERIFYHOST, 0);curl_setopt($ch_start,CURLOPT_SSL_VERIFYPEER, 0);curl_setopt($ch_start,CURLOPT_FILE,$zip_resource);$page =curl_exec($ch_start);if(!$page){echo "Error :- ".curl_error($ch_start);}curl_close($ch_start);$zip = new ZipArchive;$extractPath = "Download File Path";if($zip->open($zipFile) != "true"){echo "Error :- Unable to open the Zip File";}$zip->extractTo($extractPath);$zip->close();
class FileNotFound extends RuntimeException {}
$downloadUploadedZip = function(string $filename): void {
$directory = 'C:/xampp/htdocs/issv/upload';
if (dirname($filename) !== '.') {
$directory = dirname($filename);
}
$filename = basename($filename);
$filepath = sprintf('%s/%s', $directory, $filename);
if (file_exists($filepath)) {
header("Content-Type: application/zip");
header(sprintf("Content-Disposition: attachment; filename=%s", $filename));
header(sprintf("Content-Length: %d", filesize($filepath)));
readfile($filepath);
exit;
}
throw new FileNotFound(sprintf('File %s not found.', $filepath));
};
$downloadUploadedZip('26908557.zip');
$downloadUploadedZip('C:/xampp/htdocs/issv/upload/26908557.zip');

How can I show a PDF return from sftp-get from PHPSECLIB

I want to show to the user a PDF or a PNG that is in my SFTP server.
I am doing the connection with phpseclib to get the file.
How can I manipulate the file to show it in the browser?
$key = new RSA();
$key->loadKey(file_get_contents('*******'));
$sftp = new SFTP($fsock);
if (!$sftp->login('*******', $key)) {
exit('Bad credentials!');
}
$path = "******";
$filename = $result[0]->filefinalname ;
$file = $sftp->get($path . $filename);
Send Content-Type and file content
$file = '/path/to/temp/dir/'.uniqid(rand(), true); //temp name
file_put_contents($file,$sftp->get($path . $filename)); // save temp file
if (exif_imagetype($file)) //if this image
header("Content-Type: image/png"); //type file png
else
header("Content-type:application/pdf"); //type file pdf
header('Content-Length: ' . filesize($file)); //send size
readfile($file); //send file
unlink($file); //delete temp file

Set the name of Zip archive using ZipArchive class

The code I currently have, attached below, successfully writes files into an archive and initiates downloading of the file but the filename is a random alphanumeric string. A few examples of these file titles are:
IfTO57y8.zip
PFuuPgMD.zip
KUgWDc0T.zip
How can I set the name of the Zip folder to something more user-friendly?
function start_brochures_download( $brochures ) {
$confirmation = "Your download should begin shortly. \r\n";
$error = "Files not set \r\n";
$files = $brochures;
if( $files ) {
$zip = new ZipArchive();
$current_time = time();
$file_name = "Brochures-".$current_time;
$file_folder = wp_upload_dir();
$dir = $file_folder['path'];
$zip_file = $dir.'/'.$file_name.'.zip';
$zip->open( $zip_file, ZipArchive::CREATE );
foreach ($files as $file) {
if( !empty($file) ){
# download file
$download_file = file_get_contents($file);
#add it to the zip
$zip->addFromString(basename($file), $download_file);
}
}
$zip->close();
header('Content-disposition: attachment; filename="'.$zip_name.'"');
header('Content-type: application/zip');
header('Content-Length: ' . filesize($zip_file));
// header("Location: $zip_file");
readfile($zip_file);
} else {
echo $error;
}
}

Categories