I can't understand how my button should look and trigger download files as zip. On the page I can add files in some sort of cart and when I finish with file adding I want to download them like zip.
So what I have so far is this
<?php
include 'database.inc.php';
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if(isset($_POST['total_cart_items']))
{
echo count($_SESSION['itemid']);
exit();
}
if(isset($_POST['item_id']))
{
if (!in_array($_POST['item_id'], $_SESSION['itemid'])) $_SESSION['itemid'][]=$_POST['item_id'];
echo count($_SESSION['itemid']);
exit();
}
if(! isset($_POST['showcart'])) exit;
foreach ($_SESSION['itemid'] as $i):
$sql = "SELECT * FROM document_upload WHERE upload_id = :id";
$result = $pdo->prepare($sql);
$result->bindParam(":id", $i);
$result->execute();
$resArray = $result->fetchAll();
foreach ( $resArray as $row ):?>
<div class="cart_items">
<a style="text-align:center;" href=""><p><?=$row["upload_title"]?> - <?=$row["upload_description"]?></p></a>
</div>
<?php endforeach;?>
<?php endforeach; ?>
<a class="btn btn-info btn-sm pull-right" style="margin: 10px;" href="">Download All Files</a>
So do I need another file which will load when I click on Download All Files or?
EDIT: I found this. The problem is how to pass all the files for download to this function?
session_start();
$files = array();
$valid_files = array();
if(is_array($files)) {
foreach($files as $file) {
if(file_exists($file)) {
$valid_files[] = $file;
}
}
}
if(count($valid_files > 0)){
$zip = new ZipArchive();
$zip_name = "zipfile.zip";
if($zip->open($zip_name, ZIPARCHIVE::CREATE)!==TRUE){
$error .= "* Sorry ZIP creation failed at this time";
}
foreach($valid_files as $file){
$zip->addFile($file);
}
$zip->close();
if(file_exists($zip_name)){
// force to download the zip
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private",false);
header('Content-type: application/zip');
header('Content-Disposition: attachment; filename="'.$zip_name.'"');
readfile($zip_name);
// remove zip file from temp path
unlink($zip_name);
}
} else {
echo "No valid files to zip";
exit;
}
Related
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.
I am trying to download some files from server using a php script but when I execute the script it works fine with smaller number of file with lesser number of files to zip however when I try execution with larger no of files the server times out and also the zip generated as the result is not deleted and occupies the space on server. the php script is as follows
if(isset($_POST['download_all']))
{
$errmsg = '';
$sql = mysqli_query($conn, "select * from img WHERE gal_id = '".base64_decode($_REQUEST['Gal'])."' And uid='".$_SESSION['uid']."' order by image1 asc");
$url = "dataroot/Gallery/".base64_decode($_REQUEST['Gal'])."_".$_SESSION['uid']."/";
while($res = mysqli_fetch_array($sql)){
$filess[] = $url.$res['image1'];
echo $url.$res['image1'];
}
$files = json_encode($filess);
$files = json_decode($files);
if(is_array($files)) {
foreach($files as $file) {
if(file_exists($file)) {
$valid_files[] = $file;
}
}
}
if(count($valid_files > 0)){
$zip = new ZipArchive();
$zip_name = "total.zip";
if($zip->open($zip_name, ZIPARCHIVE::CREATE)!==TRUE){
$error .= "* Sorry ZIP creation failed at this time";
}
foreach($valid_files as $file){
$zip->addFile($file);
}
$zip->close();
if(file_exists($zip_name)){
// force to download the zip
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-Transfer-Encoding: binary");
header("Content-length: $ size");
header("Cache-Control: private",false);
header('Content-type: application/zip');
header('Content-Disposition: attachment; filename="'.$zip_name.'"');
ob_clean();
flush();
readfile($zip_name);
ignore_user_abort(true);
//remove zip file from temp path
unlink($zip_name);
}
} else {
echo "No valid files to zip";
exit;
}
}
I have updated the memory and timeout setting on the server. The issue persists. Also the zip thus formed as the result is not unlinked and consumes memory on server.
already referred to
Reading very large files in PHP
and
How to download multiple large files with php?
but unable to resolve the issue.
am calling this function to create and download zip. the create is working but my screen freezes when the system is about to download it, then shows a bunch of abstract writings without download
function zipF(){
$track = $_POST['track'];
$cartid = $_POST['cartid'];
$zip = new ZipArchive;
if ($zip->open('myzip.zip', ZipArchive::CREATE)) {
$notan = DataDB::getInstance()->select_from_where('order_image','cartid',$cartid);
foreach($notan as $row){
$zip->addFile('../img/tempfil/'.$row['image'], $row['image']);
}
$zip->close();
$archive_file_name ="myzip.zip";
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");
echo '<div class="alert alert-danger">
<strong>Error!</strong> Problem with your order details.'.$track.'
</div>';
} else {
echo 'Failed!';
}
}
I need to be able to do this.
From a form with checkbox the user select multiple images or singles images and then download it via PHP as a Zip file.
In that way it allows user to choose images he needs or not.
Here is my Code :
<form name="zips" action="download.php" method=POST>
<ul>
<li>
<input type="checkbox" class="chk" name="items[0]" id="img0" value="2015-Above-it-All"/>
<p>Above It All</p>
</li>
<li>
<input type="checkbox" class="chk" name="items[1]" id="img1" value="2015-Crocodile"/>
<p>Crocodile</p>
</li>
<li>
<input type="checkbox" class="chk" name="items[2]" id="img2" value="2015-Dandelion"/>
<p>Dandelion</p>
</li>
<li>
<input type="checkbox" class="chk" name="items[3]" id="img3" value="2015-Dearest-Sister"/>
<p>Dearest Sister</p>
</li>
<div style="text-align:center;" >
<input type="submit" id="submit" name="createzip" value="DOWNLOAD" class="subbutton-images" >
</div>
</form>
Then the PHP code:
<?php
// common vars
$file_path = $_SERVER['DOCUMENT_ROOT']."/img/press/";
if(count($_POST['file']) > 1){
//more than one file - zip together then download
$zipname = 'Forms-'.date(strtotime("now")).'.zip';
$zip = new ZipArchive();
if ($zip->open($zipname, ZIPARCHIVE::CREATE )!==TRUE) {
exit("cannot open <$zipname>\n");
}
foreach ($_POST['items'] as $key => $val) {
$files = $val . '.jpg';
$zip->addFile($file_path.$files,$files);
}
$zip->close();
//zip headers
if (headers_sent()) {
echo 'HTTP header already sent';
} else {
if (!is_file($zipname)) {
header($_SERVER['SERVER_PROTOCOL'].' 404 Not Found');
echo 'File not found';
} else if (!is_readable($zipname)) {
header($_SERVER['SERVER_PROTOCOL'].' 403 Forbidden');
echo 'File not readable';
} else {
header($_SERVER['SERVER_PROTOCOL'].' 200 OK');
header("Content-Type: application/zip");
header("Content-Transfer-Encoding: Binary");
header("Content-Length: ".filesize($zipname));
header("Content-Disposition: attachment; filename=\"".basename($zipname)."\"");
header("Pragma: no-cache");
header("Expires: 0");
readfile($zipname);
exit;
}
}
} elseif(count($_POST['items']) == 1) {
//only one file selected
foreach ($_POST['items'] as $key => $val) {
$singlename = $val . '.jpg';
}
$pdfname = $file_path. $singlename;
//header("Content-type:application/pdf");
header("Content-type: application/octet-stream");
header("Content-Disposition:inline;filename='".basename($pdfname)."'");
header('Content-Length: ' . filesize($pdfname));
header("Cache-control: private"); //use this to open files directly
readfile($pdfname);
} else {
echo 'no documents were selected. Please go back and select one or more documents';
}
?>
At the moment this script let me download a single image from the form but as soon as there is 2 images and that the script try to ZIP the files and then offer download its not working anymore.
Any ideas would be pretty nice from you guys as i'm a bit stucked with the scfript at the moment?
So below is the right PHP script which works for me :
:))
<?php
// common vars
$file_path = $_SERVER['DOCUMENT_ROOT']."/img/press/";
if(count($_POST['items']) > 1){
//more than one file - zip together then download
$zipname = 'Forms-'.date(strtotime("now")).'.zip';
$zip = new ZipArchive();
if ($zip->open($zipname, ZIPARCHIVE::CREATE )!==TRUE) {
exit("cannot open <$zipname>\n");
}
foreach ($_POST['items'] as $key => $val) {
$files = $val . '.jpg';
$zip->addFile($file_path.$files,$files);
}
$zip->close();
//zip headers
if (headers_sent()) {
echo 'HTTP header already sent';
} else {
if (!is_file($zipname)) {
header($_SERVER['SERVER_PROTOCOL'].' 404 Not Found');
echo 'File not found';
} else if (!is_readable($zipname)) {
header($_SERVER['SERVER_PROTOCOL'].' 403 Forbidden');
echo 'File not readable';
} else {
header('Content-type: application/zip');
header('Content-Disposition: attachment; filename='.$zipname);
header('Pragma: no-cache');
header('Expires: 0');
readfile($zipname);
flush();
if (readfile($zipname))
{
unlink($zipname);
}
//unlink($zipname);
exit;
}
}
} elseif(count($_POST['items']) == 1) {
//only one file selected
foreach ($_POST['items'] as $key => $val) {
$singlename = $val . '.jpg';
}
$pdfname = $file_path. $singlename;
//header("Content-type:application/pdf");
header("Content-type: application/octet-stream");
header("Content- Disposition:inline;filename='".basename($pdfname)."'");
header('Content-Length: ' . filesize($pdfname));
header("Cache-control: private"); //use this to open files directly
readfile($pdfname);
} else {
echo 'no documents were selected. Please go back and select one or more documents';
}
?>
***<?php
// common vars
$file_path = $_SERVER['DOCUMENT_ROOT']."/img/press/";
if(count($_POST['items']) > 1){
//more than one file - zip together then download
$zipname = 'Forms-'.date(strtotime("now")).'.zip';
$zip = new ZipArchive();
if ($zip->open($zipname, ZIPARCHIVE::CREATE )!==TRUE) {
exit("cannot open <$zipname>\n");
}
foreach ($_POST['items'] as $key => $val) {
$files = $val . '.jpg';
$zip->addFile($file_path.$files,$files);
}
$zip->close();
//zip headers
if (headers_sent()) {
echo 'HTTP header already sent';
} else {
if (!is_file($zipname)) {
header($_SERVER['SERVER_PROTOCOL'].' 404 Not Found');
echo 'File not found';
} else if (!is_readable($zipname)) {
header($_SERVER['SERVER_PROTOCOL'].' 403 Forbidden');
echo 'File not readable';
} else {
header('Content-type: application/zip');
header('Content-Disposition: attachment; filename='.$zipname);
header('Pragma: no-cache');
header('Expires: 0');
readfile($zipname);
flush();
if (readfile($zipname))
{
unlink($zipname);
}
//unlink($zipname);
exit;
}
}
} elseif(count($_POST['items']) == 1) {
//only one file selected
foreach ($_POST['items'] as $key => $val) {
$singlename = $val . '.jpg';
}
$pdfname = $file_path. $singlename;
//header("Content-type:application/pdf");
header("Content-type: application/octet-stream");
header("Content- Disposition:inline;filename='".basename($pdfname)."'");
header('Content-Length: ' . filesize($pdfname));
header("Cache-control: private"); //use this to open files directly
readfile($pdfname);
} else {
echo 'No Document were selected .Please Go back and Select Document again';
}
?>***
I have a custom page for specific products of a category.
here is the link and code by which I am showing all the images only.
<div style="float:left; width:100%;">
<?php $_helper = $this->helper('catalog/output'); ?>
<?php $product = $this->getProduct(); ?>
<?php foreach ($product->getMediaGalleryImages() as $image) :?>
<div style="width: 48%; margin:1%;float:left">
<img width="100%;" src="<?php echo Mage::helper('catalog/image')->init($product, 'image', $image->getFile()); ?>" alt="<?php echo $product->getName()?>" />
</div>
<?php endforeach; ?>
</div>
<div style="float:left; width:100%;">
<button type="button" style="display:block;margin:0 auto;">Download</button>
</div>
Now I need to download all the images of product on click of the button, the link is
http://thevastrafashion.com/english/testing-1.html
How can I achieve this. If you want anything more please leave a comment.
You can do following to achieve this.
foreach ($sku as $key => $value) {
$productId = $value;
$products = Mage::getModel('catalog/product')->loadByAttribute('sku', $productId);
$inStock = Mage::getModel('cataloginventory/stock_item')->loadByProduct($products)->getIsInStock();
if($inStock)
{
array_push($file_arr, (string) Mage::helper('catalog/image')->init($products, 'image'));
}
}
if(count($file_arr)>0)
{
$result = create_zip($file_arr);
}
function create_zip($files = array()) {
try{
$zip = new ZipArchive();
$tmp_file = tempnam('.', '');
$zip->open($tmp_file, ZipArchive::CREATE);
foreach ($files as $file) {
$download_file = file_get_contents($file);
$zip->addFromString(basename($file), $download_file);
}
$zip->close();
header('Content-disposition: attachment; filename=download.zip');
header('Content-type: application/zip');
header("Accept-Ranges: bytes");
header("Pragma: public");
header("Expires: -1");
header("Cache-Control: public, must-revalidate, post-check=0, pre-check=0");
header('Content-Length: ' . filesize($tmp_file));
$chunksize = 8 * (1024 * 1024); //8MB (highest possible fread length)
$handle = fopen($tmp_file, 'rb');
$buffer = '';
while (!feof($handle) && (connection_status() === CONNECTION_NORMAL))
{
$buffer = fread($handle, $chunksize);
print $buffer;
ob_flush();
flush();
}
if(connection_status() !== CONNECTION_NORMAL)
{
echo "Connection aborted";
}
fclose($handle);
}
catch(Exception $e)
{
Mage::log($e,null,'download_error.log');
}
}
This is reference code only. So you need to change according to your requirement.