Fetch PDF from BLOB and create zip in PHP - php

I have blob stored in Database and successfully converted it into PDF. I am using this code.
header('Content-type: application/pdf');
header("Cache-Control: no-cache");
header("Pragma: no-cache");
header("Content-Disposition: attachment;filename=".$this->pdfName);
header("Content-length: ".strlen($res[0]['comp_statement']));
$this->pdf = $res[0]['comp_statement']
echo $res[0]['comp_statement'];
There are two option in Content-Disposition ethier you can download it or show it on web page.
I do not want to show or download. I want it to place in zip directory which I am creating dynamically.
Here the code for zip archive
$zip = new ZipArchive;
$zipName = $this->currentCompYear.'.zip';
if ($zip->open($zipName, ZipArchive::CREATE | ZipArchive::OVERWRITE) === TRUE) {
if(!$zip->locateName($this->currentCompYear)) {
$zip->addEmptyDir($this->currentCompYear);
}
if(!$zip->locateName($regionDir)) {
$zip->addEmptyDir($regionDir1);
}
if(!$zip->locateName($managerDir)) {
$zip->addEmptyDir($managerDir1);
}
$zip -> addFile($this->pdf));// I want to add my pdf file here
$zip->close();
ob_clean();
header("Content-type: application/zip");
header("Content-Disposition: attachment; filename=".$zipName);
header("Content-length: " . filesize($zipName));
header("Pragma: no-cache");
header("Expires: 0");
readfile($zipName);
Any Clue.

You dont need any of that header and echo stuff if you just want to store the contents to a file, use file_put_contents() to store the pdf, then pass the file name and not the contents to addFile() of your Zip function
https://www.php.net/manual/en/function.file-put-contents.php

Related

why does an empty pdf file created in the same folder when i click download every time?

i was trying to force download pdf files on my website. The file was downloaded successfully but an empty file is created in the same folder with a random name when download is clicked. i'm having multiple null files in the folder.
download.php :
<?php
$file = $_GET['file'];
header('Content-type: application/pdf');
header('Content-Length: ' . filesize($file));
header('Content-Disposition: attachment; filename="'.$file.'"');
?>
Assuming you store your pdf in database.
//you need to decode
$decoded = base64_decode($downloaded->pdf);
//name of pdf
$filename =date('Ymdhis').'.pdf';
$size=strlen($decoded);
header('Content-Description: File Transfer');
header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename="'.($filename).'"');
header("Content-Transfer-Encoding: binary");
header('Expires: 0');
header("Cache-Control: no-cache, must-revalidate");
header("Pragma: no-cache");
header('Content-Length:'.$size);
echo($decoded);
exit;
Please note, if you send some headers before it will not working.
Make sure you create properly your pdf file.
$decoded = base64_decode($downloaded->pdf);
$filename =date('Ymdhis').'.pdf';
//if file doesn't exists
if(!file_exists($filename)){
//we create file in the location
$fp=fopen($_SERVER['DOCUMENT_ROOT'].'/tmp/'.$dir_name.''.$filename,'a+');
//We write in
fwrite($fp, $decoded);
}

Php or Apache? Content of zip file is diplayed instead of downloading zip file

I tried to write a php-script to create and download a zip file. When I tested the script on my localhost, the download works, but when it's uploaded to the server, things go wrong: instead of downloading the zip file, the content of the file is displayed in the browser.
Can somebody point me in the right direction?
The code
$zip = new ZipArchive();
$zip->open("$maand/zipfile.zip", ZipArchive::OVERWRITE);
$zip->addFile("$maand/ant/a_nb.txt", 'ant.txt');
$zip->addFile("$maand/lim/l_nb.txt", 'lim.txt');
$zip->addFile("$maand/oos/o_nb.txt", 'oos.txt');
$zip->addFile("$maand/vla/v_nb.txt", 'vla.txt');
$zip->addFile("$maand/wes/w_nb.txt", 'wes.txt');
$zip->close();
$filename = "zipfile.zip";
$filepath = "$maand/";
// headers for zip downloads
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: public");
header("Content-type: application/zip");
header("Content-Disposition: attachment; filename=\"".$filename."\"");
header("Content-Length: ".filesize($filepath.$filename));
ob_end_flush();
#readfile($filepath.$filename);
you missing ob_start()
example:
header('Content-Type: application/csv');
header('Content-Disposition: attachement; filename="' . $download . '"');
ob_start();
$str = '';
if(file_exists($file) === true){
$str = file_get_contents($file);
}
ob_end_clean();
echo $str;

php - file_get_contents() for dynamic script

I have a script that outputs an image.
Works fine
include('../myfolder/myImageScript.php'); // outputs image on page
Fails
echo file_get_contents('../myfolder/myImageScript.php'); // nothing displayed
I think this fails because in php a script, in my case myImageScript.php, isn't executed when called via the file_get_contents() function, but is when called using a include() the script is executed.
I am struggling to get a zip function to work due to the empty output of file_get_contents().
the file i'm trying to call via file_get_contents() is:
myImageScript.php
$imgstr = "data:image/jpeg;base64,/9j/........... rest of string";
if (!preg_match('/data:([^;]*);base64,(.*)/', $imgstr, $matches)) {
die("error");
}
// Decode the data
$content = base64_decode($matches[2]);
// Output the correct HTTP headers
header('Content-Type: '.$matches[1]);
//header("Content-Type: image/jpeg"); // tried this made no difference
// Output the actual image data
echo $content;
Any help would be greatly appreciated.
Something like this should work, BUT you need to enable ZipArchive http://php.net/manual/en/class.ziparchive.php (should not be a problem)
<?php
$imgstr = "data:image/gif;base64,R0lGODlhyAAiALMAAFONvX2pzbPN4p6/2tTi7mibxYiw0d/q86nG3r7U5l2UwZO31unx98nb6nOiyf///yH5BAUUAA8ALAAAAADIACIAAAT/8MlJq7046827/2AojmRpnmiqriwGvG/Qjklg28es73wHxz0P4gcgBI9IHVGWzAx/xqZ0KlpSLU9Y9MrtVqzeBwFBJjPCaC44zW4HD4TzZI0h2OUjON7EsMd1fXcrfnsfgYUSeoYLPwoLZ3QTDAgORAoGWxQHNzYSBAY/BQ0XNZw5mgMBRACOpxSpnLE3qKqWC64hk5WNmBebnA8MjC8KFAygMAUCErA2CZoKq6wHkQ8C0dIxhQRED8OrC1hEmQ+12QADFebnABTr0ukh1+wB20QMu0ASCdn16wgTDmCTNlDfhG/sFODi9iMLvAoOi6hj92LZhHfZ3FEEYNEDwnMK/ykwhDEATAN2C/5d3PiDiYSIrALkg6EAz0hiFDNFJKeqgIEyM1nhwShNo0+glhBhgKlA5qqaE25KY1KAYkGAYlYVSEAgQdU1DFbFe3DgKwysWcHZ+QjAAIWdFQaMgkjk2b4ySLtNkCvuh90NYYmMLUsErVRiC8o8OLmkAYF5hZkRKYCHgVmDAiJJLeZpVUdrq/DA7XB5rAV+gkn/MJ0hc8sKm6OuclDoo8tgBQFgffd335p3cykEjSK1gIXLEl+Oq9OgTIKZtymg/hHuAoHmZJ6/5gDcwvDOyysEDS7B9VkJoSsEhuEyN6KSPyxKrf4qsnIoFQ4syL0qum8i9AW0H/9F/l3gngXwwSAfEQ5csIoFUmH1oAVrTEhXQ+Cdd6GGD4z230b+TQdDgB8S6INeG76AlVSsoYeibBg+cOAX2z1g4Vv2sYggER15uFliZFwWnUAAQmhLGUKe+MMFEa1oH40/FMKYht1RMKVB7+AiwTvEMehdeB2CicwLlAlXI1m5kSjBmACUOQF0HWRpAZcZqngBbxWwqZtkZz4QlEsJvkDiejDIcRh5h4kG5pPBrEHkDw06GKMEhAJwGxx+uBIoAIOmlxaH9TWCh4h2fgqDAWcc019AqwTHwDtu1UmMRQnkdpuHRU6gZ3uWOOaHILmuScc6LlFDhKuwwgiqsjQNgAD/UWgFZaKuq/w0AHIAuHIYReR5+A4C12HkEksSfRvuqiuxR4GebSFw7SraMqoRuXvK2t+Z+JDb22bsxDqBh+YRVCO5RgT81JnEGiNtNvvKKwl/IzJKql8ORadqQuSZis7CANCWYnIScOyAiJHayFIUIpM8r0GUstsrbA4HhC2nJi9LwDuihKkuhEQpgAAiEQpjyc99aWHMppz2gSLBlCL9iFQrW2pdz0TDPCkGCRgQjU9GVPpZQAkgIICWHfQhABkNkM1svQxg9wcJfWSn1AlxI5DA3COYjbbaLJBKzhQRuiF4Cn8nMiMXgQ+uOAkBFDDA2wxABkPJiMe8+OUaECVNLMZUJI755xtoHmwXnoNuugUQp4bGLzf0dvrriy2wsAMD4A377YJjSgDfD0QAADs=";
if (!preg_match('/data:([^;]*);base64,(.*)/', $imgstr, $matches)) {
die("error");
$content = base64_decode($matches[2]);
$zip = new ZipArchive;
$filename = tempnam("/tmp", "testmeZip");
$res = $zip->open($filename, ZipArchive::CREATE);
if ($res === TRUE) {
$zip->addFromString('test.gif', $content);//you can use $matches to figure out extension
$zip->close();
echo 'ok';
} else {
echo 'failed';
}
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=\"test.zip\"");
header("Content-Transfer-Encoding: binary");
// make sure the file size isn't cached
clearstatcache();
header("Content-Length: ".filesize($filename));
// output the file
readfile($filename);

Forcing php to download a file inside zip

I have a file image.php that dynamically views an image inside a Zip folder.
So image.php?location=./folder/Hi.zip&file=image.jpg views the image.
I have another file downloadfile.php that forces download of file specified in the parametes.
downloadfile.php?location=.folder/&file=image.jpg* downloads the image*
What I need is to download the dynamically generated image (by image.php) using downloadfile.php.
downloadfile.php
<?php
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
$file=$_GET['file'];$ext=$_GET['ext'];$location=$_GET['location'];
header('Content-disposition: attachment; filename="'.$file.'"');
header('Content-type:"'.$ext.'"');
readfile("$location"."$file");
?>
image.php
<?php
function showimage($zip_file,$file_name)
{
$z=new ZipArchive();
if($z->open($zip_file)!=true){
echo "File not found";
return false;
}
$stat=$z->statName($file_name);
$fp=$z->getStream($file_name);
if(!$fp){
echo "Could not load image";
return false;
}
header('Content-Type:image/'.$_GET['type']);
header('Content-Length:'. $stat['size']);
fpassthru($fp);
return true;
}
showimage($_GET['zip'],$_GET['file']);
?>
Any suggestions??
In order to force browser to download an image file you can use the code from image.php
and just change the header
from
header('Content-Type:image/'.$_GET['type']);
header('Content-Length:'. $stat['size']);
to
header("Content-Transfer-Encoding: binary");
header('Content-Description: File Transfer');
header('Content-Type:image/'.$_GET['type']);
header('Content-Length: ' . $stat['size']);
header('Content-Disposition: attachment; filename=' . $file_name);
this will force user to download instead of display an image.

Path Name and Zip File Name showing when downloading Zip file In PHP

I am trying to write a PHP program which delivers a zip file for download. I have searched on the internet and tried all the solutions but my issue is not getting solved.
My problem is when the zip file is downloaded to a user's computer the entire path is displayed as the name of the zip file.
For Example:
Path to the Zip File: "http://www.websitename.com/folder1/folder2/"
Name of Zip File: "zbc123.zip"
When the Browser downloads the zip file, the Name of the file is as follows:
http-_www.websitename.com_folder1_folder2_zbc123.zip
I do not want the path to be the name of the downloaded zip file.
I only want the actual zip file to be displayed.
Here is my codespec:
$m_item_path_name = "http://www.websitename.com/folder1/folder2/";
$m_zip_file_name = "zbc123.zip"
//Combining the Path and the Zip file name and storing into memory variable
$m_full_path = $m_item_path_name.$m_zip_file_name;
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=\"".$m_zip_file_name."\"");
header("Content-Transfer-Encoding: binary");
header("Content-Length: ".filesize($m_item_path_name.$m_zip_file_name));
ob_end_flush();
#readfile($m_item_path_name.$m_zip_file_name);
Can anyone help me to solve this issue.
Any kind of help will be appreciated.
Thanks a lot.
try this:
<?php
$file_names = array('file1.pdf','file2.pdf');
//Archive name
$archive_file_name=$name.'Name_u_want.zip';
//Download Files path
$file_path=$_SERVER['DOCUMENT_ROOT'].'/files/';
zipFilesAndDownload($file_names,$archive_file_name,$file_path);
function zipFilesAndDownload($file_names,$archive_file_name,$file_path)
{
//echo $file_path;die;
$zip = new ZipArchive();
//create the file and throw the error if unsuccessful
if ($zip->open($archive_file_name, ZIPARCHIVE::CREATE )!==TRUE) {
exit("cannot open <$archive_file_name>\n");
}
//add each files of $file_name array to archive
foreach($file_names as $files)
{
$zip->addFile($file_path.$files);
}
$zip->close();
//then send the headers to foce download the zip file
header("Content-type: application/zip");
header("Content-Disposition: attachment; filename=$archive_file_name");
header("Content-length: " . filesize($archive_file_name));
header("Pragma: no-cache");
header("Expires: 0");
readfile("$archive_file_name");
exit;
}
?>

Categories