Add excel file to password protected zip? - php

How do I add a generated excel file to a password protected zip and download it?
I am using ZipArchive library. I am trying to add the excel file to zip but unfortunately zip is not getting generated.
if(isset($_POST["export_excel"]))
{
$sql = "SELECT * FROM Datas ORDER BY ID DESC";
$result = mysqli_query($connect, $sql);
....
....
....
$output .= '</table>';
$fileName = "DB".date('Y_m_d').".xls";
header("Content-Type: application/xls");
header("Content-Disposition: attachment; filename=$fileName");
echo $output;
$zip = new ZipArchive;
$tmp_file = 'myzip.zip';
if ($zip->open($tmp_file, ZipArchive::CREATE)) {
$zip->setPassword>addFile('PASSWORD', $fileName);
$zip->setEncryptionName($fileName, ZipArchive: header('Content-disposition:EM_AES_256 attachment; filename=files.zip');
header('Content-type: application/zip');
$zip->close();
readfile($tmp_file);
}
}

I got it. If anyone needs it, the logic was to add contents of the database in excel and then output it.
$output .= '</table>';
$fileName = "DB".date('Y_m_d').".xls";
header("Content-Type: application/xls");
header("Content-Disposition: attachment; filename=$fileName");
//echo $output;
file_put_contents($fileName, $output);
}
}
$zip = new ZipArchive;
$tmp_file = 'myzip.zip';
if ($zip->open($tmp_file, ZipArchive::OVERWRITE|ZipArchive::CREATE)) {
$zip->setPassword('PASSWORD');
$zip->addFile($fileName);
$zip->setEncryptionName($fileName, ZipArchive::EM_AES_256);
header('Content-disposition: attachment; filename=files.zip');
header('Content-type: application/zip');
readfile($tmp_file);
}

Related

Creating zipped file of many pdfs automatically

I am trying to zip a series of pdf files automatically when a page loads. The files are based on a query. I can't seem to figure out the error. All of the pdfs are kept in the agreements folder and I want the zip file to just download on the viewer's computer. The error code that I get is:
agreements/Acadience_Cambridge_Post_1.pdfagreements/DoTheMath_Cambridge.pdfagreements/Edulog_Cambridge.pdfagreements/DESSA_Cambridge.pdfagreements/FuelEducation_Cambridge_signed.pdfagreements/LegendsofLearning_Dedham.pdfagreements/workforce19-22.pdfagreements/Ellevation_Dedham_Posting.pdfagreements/Yabla_Cambridge.pdfagreements/Breakthrough-2020.pdfagreements/Cedar-Labs-DPA.pdfagreements/Tutoring Plus.pdfagreements/Elefante Letrado_Brockton - post.pdfagreements/CollegeBoard_Cambridge_post_1.pdfagreements/LanguageConnections_post.pdfagreements/Flat_Westford - post.pdfagreements/Albert.io_Cambridge_post.pdfagreements/Starfall_Walpole.pdfagreements/Tynker_Milton - post_1.pdfagreements/WeVideo_CambridgeTEC_1.pdfagreements/Checkology_Dedham.pdfagreements/BabylonHouse _Cambridge_signed_4.pdfagreements/FreeMath_Westwood_Post.pdf
Warning: ZipArchive::close(): Failure to create temporary file: Permission denied in /var/www/html/extract_dpas2.php on line 36
Could not find Zip file to download
Here is the code I have:
<?php require_once('Connections/sdpc_i.php'); ?>
<?php
ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
error_reporting(E_ALL);
$sql = "SELECT * FROM data WHERE districtID = 457 and statusID=1 and signed_agreement_file != 'NULL'";
if ($result=mysqli_query($sdpc_i,$sql))
{
// $rowcount=mysqli_num_rows($result);
// printf("Result set has %d rows.\n",$rowcount);
//define array for storing files
$file = array();
while ($row = mysqli_fetch_assoc($result)) {
//give file name with extension
$name ="agreements/".$row['signed_agreement_file'];
//store file name in array
$file[] = $name;
// store file in one folder named 'files'
file_put_contents($name,$row["signed_agreement_file"]);
}
$zipname = "file.zip";
$zip = new ZipArchive();
$zip_name = time().".zip"; // Zip name
$zip->open($zip_name, ZipArchive::CREATE);
foreach ($file as $f) {
echo $path = "".$f;
if(file_exists($path)){
$zip->addFromString(basename($path), file_get_contents($path));
}
else{
echo"file does not exist";
}
}
$zip->close();
//check zip file create or not and download it
if (file_exists($zipname)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . basename($zipname).'"');
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($zipname));
ob_clean();
flush();
readfile($zipname);
exit;
} else {
exit("Could not find Zip file to download");
}
mysqli_free_result($result);
mysqli_close($conn);
}
?>
Thank you in advance for you help.

$zip -> addFile not working

Trying to create a zip-file with different pdf-files where I get the names on the pdf-files from checkboxes in a form.
I get the code to download a zip-file, but when I try to open it it say that
the zip is invalid. Sometimes I get no error but a empty folder. So it seems like $zip->addFile does not add the file.
Here is the code:
<?php
$test = $_POST['check'];
$zip = new ZipArchive;
if (!empty($_POST['check']))
{
$tmp_file = 'zip/myzip.zip';
if ($zip->open('myzip.zip') === TRUE)
{
foreach($_POST['check'] as $check)
{
$zip->addFile('pdf/' . $check, $check);
}
echo $tmp_file;
$zip->close();
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-type: application/zip");
header("Content-Disposition: attachment; filename=\"" . $tmp_file . "\"");
header("Content-Transfer-Encoding: binary");
readfile($tmp_file);
ob_end_flush();
} else {
echo 'failed';
}
} else {
echo 'Ingen vald';
}
?>

Zip download issue in php

if(isset($_REQUEST['create_all']))
{
$app_id = $_REQUEST['app'];
$fullpath = array();
$dir = dirname(__FILE__);
foreach($language_array as $key_lang=>$name_lang)
{
$path = $dir."/uploaded_xml/".$app_id."/";
if(!is_dir($path))
{
mkdir($path,0777);
chmod($path,0755);
}
$QUERY=mysql_query("select a.process_flag,a.field_id,a.field_name,a.xml_status,b.*,c.process_flag,b.lang_id from app_lang_fieldmaster_new a left join app_lang_translatetxt_new b on a.field_id=b.field_id left join app_lang_user_status c on a.field_id=c.field_id left join app_wise_lang_fields d on a.field_id=d.field_id where a.process_flag='0' and c.process_flag='6' and b.lang_id='".$key_lang."' and a.xml_status='1' and a.module_master_id='1' and d.app_id='".$app_id."' group by 2",$cont);
//create the xml document
$xmlDoc = new DOMDocument("1.0", "UTF-8");
//create the root element
$root = $xmlDoc->appendChild(
$xmlDoc->createElement("resources"));
while($row=mysql_fetch_object($QUERY))
{
if($key_lang==9)
{
$xml_string = $xmlDoc->createElement( "string",trim($row->translate," "));
$xml_string->setAttribute( "name",$row->field_name);
$root->appendChild($xml_string);
}
else
{
$xml_string = $xmlDoc->createElement( "string",trim(base64_decode($row->translate)," "));
$xml_string->setAttribute( "name",$row->field_name );
$root->appendChild($xml_string);
}
}
header("content-type: text/plain; charset=ISO-8859-15");
//make the output pretty
$xmlDoc->formatOutput = true;
$string = $xmlDoc->saveXML();
$handle = fopen($path.$name_lang.".xml","w");
fwrite($handle,$string);
fclose($handle);
// $string = $xmlDoc->save($path.$name_lang.".xml");
$fullpath[$key_lang] = $path.$name_lang.".xml";
}
ob_clean();
flush();
//zip file creation
$zip = new ZipArchive();
//zip file name
$FilePath = $app_id.".zip";
$full_path_zip = 'https://'.$_SERVER['HTTP_HOST'].dirname($_SERVER['PHP_SELF'])."/".$FilePath;
//check if file exists if yes then delete
if(file_exists(dirname(__FILE__)."/uploaded_xml/".$FilePath))
{
unlink (dirname(__FILE__)."/uploaded_xml/".$FilePath);
}
//open zip file to add files to zip file
if ($zip->open(dirname(__FILE__)."/uploaded_xml/".$FilePath, ZIPARCHIVE::CREATE) != TRUE)
{
die ("Could not open archive");
}
//$zip->addFile("file_path","file_name");
// loop through each file
foreach($language_array as $key=>$name)
{
//add files to zip
$zip->addFile($fullpath[$key],$name.".xml");
}
// close and save archive
$zip->close();
// header_remove();
echo $full_path_zip;
ob_clean();
flush();
$filename = dirname(__FILE__)."/uploaded_xml/".$FilePath;
header('Cache-Control: public');
header('Content-Description: File Transfer');
header('Content-type: application/zip');
header('Content-Disposition: attachment; filename="'.$filename.'"');
// echo dirname(__FILE__)."/uploaded_xml/".$FilePath;
str_replace(".php",".zip",$filename);
$file_content = file_get_contents($filename); // To download the ZIP file
print($file_content);
}
i am creating a zip file which contains some xml files from server, i am adding that xml files to zip and then trying to download the zip but it is downloading .php file. here is my code
$xmlDoc = new DOMDocument("1.0", "UTF-8");
//create the root element
$root = $xmlDoc->appendChild(
$xmlDoc->createElement("resources"));
while($row=mysql_fetch_object($QUERY))
{
if($key_lang==9)
{
$xml_string = $xmlDoc->createElement( "string",trim($row->translate," "));
$xml_string->setAttribute( "name",$row->field_name);
$root->appendChild($xml_string);
}
else
{
$xml_string = $xmlDoc->createElement( "string",trim(base64_decode($row->translate)," "));
$xml_string->setAttribute( "name",$row->field_name );
$root->appendChild($xml_string);
}
}
header("content-type: text/plain; charset=ISO-8859-15");
//make the output pretty
$xmlDoc->formatOutput = true;
$string = $xmlDoc->saveXML();
$handle = fopen($path.$name_lang.".xml","w");
fwrite($handle,$string);
fclose($handle);
// $string = $xmlDoc->save($path.$name_lang.".xml");
$fullpath[$key_lang] = $path.$name_lang.".xml";
}
ob_clean();
flush();
//zip file creation
$zip = new ZipArchive();
//zip file name
$FilePath = $app_id.".zip";
$full_path_zip = 'https://'.$_SERVER['HTTP_HOST'].dirname($_SERVER['PHP_SELF'])."/".$FilePath;
//check if file exists if yes then delete
if(file_exists(dirname(__FILE__)."/uploaded_xml/".$FilePath))
{
unlink (dirname(__FILE__)."/uploaded_xml/".$FilePath);
}
//open zip file to add files to zip file
if ($zip->open(dirname(__FILE__)."/uploaded_xml/".$FilePath, ZIPARCHIVE::CREATE) != TRUE)
{
die ("Could not open archive");
}
//$zip->addFile("file_path","file_name");
// loop through each file
foreach($language_array as $key=>$name)
{
//add files to zip
$zip->addFile($fullpath[$key],$name.".xml");
}
// close and save archive
$zip->close();`
here is my download zip file
$file_content = file_get_contents(dirname(__FILE__)."/uploaded_xml/".$FilePath); // To download the ZIP file
header('Cache-Control: public');
header('Content-Description: File Transfer');
header('Content-type: application/force-download');
header('Content-Disposition: attachment; filename="'.dirname(__FILE__)."/uploaded_xml/".$FilePath.'"');
echo $file_content;
it is downloading .php file with following content
PK ”R—I+ Qý
Bulgarian.xml­”ÁnÓ#†ï}Š•ïP¸õ¤B J•Z‰pµ{’X²×ÑzàR ¢¤ŠBHo`ª˜†¤q_aöø×NÔÕ*nkÏÎ73ÿÌlk÷U‰—¤Ò0‘mçáýŽ é'A(ûmçù³½{;Îng«¥(M2åSÚÙ¢•j»^Lm§§B’AêFÝÈ]žå’§fÌ…à+3Âñ£ýà9O[Ûµ{3i˜E‘«WQq–â'32'|Å.jî‚sž ÌÜ raÞØß%‡©äóM¡ü§«Œ»*ñßK5"|æÀNÌ1|s§Ù¨(³Ø푧3EnªÉ‹ôà0  ou­f,PzÁ?xʗͬHö‡iêÊDº²ïõÉ•®ï©JÅ3ÔqÁPr[ÏRÂOÏ8‡ cü<ÆyC©ûÒû/€’ÇÑA¥ä©yî-ù°êà°àíªµô*TèGYp¸¸ËŒó†…íË?H2ýt iÅGƒÖ#üú]~ÇßQ•Ã4XOúÝ+±GOŒl£,vnsÌÊä/øHû6<f‚/ïš6°÷šâÜsä8Z-¦ÔŸ<ß°WX€Úÿ‹²ù"IMêúö)V±lÚu¬Ùf÷=ϧ'¤É׉:ðºT=µ/ϬÄf$°9¹°/Žy_YÊk\k{íAûPK ”R—I„üa[€ Î Catalan.xml“ËN+1†÷<E”=—³c1„¸HH ±èa¹‰gj)—ÊI*x(6‡Gè‹áiT!¦=›(·ï÷Ûi®^ƒWkäL)ÎôŸ³­0Úä(ö3ýw~z©¯Ú“†1§Ês{¢T“˹Šp¦;&Œ.¿ðfœëöÎg°flnÎwÄ4¼ªÞ›’c'¡–ƒ˜nçÄÀ
Öà½Z!«Ý¡žÖ³K(['Nà,ä¢Û[êj¦ÍÇ4µbTƒéJe4¹ ...
If i change the extension of downloaded file from .php to .zip it is working fine.
Kindly help thanks in advance...
Remove this line:
echo $file_content;
// To download the ZIP file
header('Cache-Control: public');
header('Content-Description: File Transfer');
header('Content-type: application/force-download');
header('Content-Disposition: attachment;
filename="'.dirname(__FILE__)."/uploaded_xml/".$FilePath.'"');
Try this
$file_content = file_get_contents(dirname(__FILE__)."/uploaded_xml/".$FilePath); // To download the ZIP file
header('Cache-Control: public');
header('Content-Description: File Transfer');
header('Content-type: application/force-download');
header('Content-Disposition: attachment; filename="'.dirname(__FILE__)."/uploaded_xml/".$FilePath.'"');

download file using php, file is stored in a folder and name of the file is stored in database

I am trying to download a file from mysqli database using php for that i have stored file in a folder and file name is stored in the mysqli database.
here is my code...
$query= mysqli_query($dbo,"SELECT * FROM diff_questions WHERE email = ' $email ' and status= '0' ");
$rows=mysqli_fetch_array($query);
$file=$rows['file'];
$path='http://localhost/admin1/uploads';
?>
echo "<a href='download.php?file=".$file."&path=".$path." '>Download File</a> ";
and now
download.php-
<?php
$file = $_GET["file"];
$path = $_GET["path"];
$fullfile = $path.$file;
header("Content-Type: application/octet-stream");
header("Content-Disposition: attachment; filename=" . Urlencode($file));
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header("Content-Description: File Transfer");
header("Content-Length: " . Filesize($fullfile));
flush();
$fp = fopen($fullfile, "r");
while (!feof($fp))
{
echo fread($fp, 65536);
flush();
}
fclose($fp);
?>
Can someone please tell me what is wrong with code. Its not working .
i mean it working file till saving file but its not downloading full file imean afther downloading file size of file is 0kb
Once replace your download.php with following code and check if its working for you or not :
if(isset($_GET["file"])){
$file = $_GET["file"];
$path = $_GET["path"];
$fullfile = $path.$file;
header("Content-Type: application/octet-stream");
header("Content-Disposition: attachment; filename=" . Urlencode($file));
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header("Content-Description: File Transfer");
$fp = fopen($fullfile,'r');
while ($line = fgets($fp)) {
echo($line);
}
fclose($fp);
}

PHP file Download without saving to my directory?

I have to create one text file and make it downloadable without saving to my directory on button click.
Below I have mentioned code of my file that generate file.
<?php
$data = "ffff dfjdhjf jhfjhf f f hlm hoejrherueirybgb,nvbd;ihrtmrn.";
$filename = "SU_Project_Startup.txt";
$fh = fopen($filename, "w+");
fwrite($fh, $data, strlen($data));
fclose($fh);
header('Content-type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . $filename . '"');
ob_end_flush();
echo $data;
exit();
?>
Can you tell me which changes still I have to do in this code?
Thanks in advance
Try this headers:
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=$file");
header("Content-Type: application/json"); // here is your type
header("Content-Transfer-Encoding: binary");
This is an example of taking pictures of the url
you can try it, or put it into function
<?php
header('Content-type: application/octet-stream');
header('Content-Disposition: attachment; filename="File-name.jpg"');
$fileurl = 'http://upload.wikimedia.org/wikipedia/commons/thumb/c/cc/Ramses_II_at_Kadesh.jpg/120px-Ramses_II_at_Kadesh.jpg';
$data = file_get_contents($fileurl);
echo $data;
?>

Categories