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';
}
?>***
Related
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 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;
}
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.
I use ZipArchive to create zip file. It all works well except one thing - downloading it as attachment. When I try to open downloaded file 7-zip says : "Can't open file .... as archive". There's everything allright with the file saved on the server. When I tried to compare downloaded file with the file stored on the server there's small difference in the end of the file.
To put it simply: archive on the server opens but after downloading it it doesn't
The code I use :
$file='Playlist.zip';
if (headers_sent()) {
echo 'HTTP header already sent';
} else {
if (!is_file($file)) {
header($_SERVER['SERVER_PROTOCOL'].' 404 Not Found');
echo 'File not found';
} else if (!is_readable($file)) {
header($_SERVER['SERVER_PROTOCOL'].' 403 Forbidden');
echo 'File not readable';
} else {
header($_SERVER['SERVER_PROTOCOL'].' 200 OK');
header("Content-Type: application/zip");
header("Content-Length: ".filesize($file));
header("Content-Disposition: attachment; filename=".basename($file)."");
header("Pragma: no-cache");
header("Expires: 0");
set_time_limit(0);
$handle = fopen($file, "rb");
while (!feof($handle)){
echo fread($handle, 8192);
}
fclose($handle);
}
}
Try using fpassthru():
$file="Playlist.zip";
if (headers_sent()) {
echo "HTTP header already sent";
} else {
if (!is_file($file)) {
header($_SERVER['SERVER_PROTOCOL'] . " 404 Not Found");
echo "File not found";
} else if (!is_readable($file)) {
header($_SERVER['SERVER_PROTOCOL'] . " 403 Forbidden");
echo "File not readable";
} else {
header($_SERVER['SERVER_PROTOCOL'] . " 200 OK");
header("Content-Type: application/zip");
header("Content-Length: " . filesize($file));
header("Content-Disposition: attachment; filename=" . basename($file));
header("Pragma: no-cache");
$handle = fopen($file, "rb");
fpassthru($handle);
fclose($handle);
}
}
Perform a $data=ltrim($data) to remove the leading blanks in the downloaded ZIP file.
this code is doing Zip & Download perfect but i want to change a time to date how can i do this
when i save a folder its save with time i want to save with date how can i do this
this is time script how can i change in to date when i change Y-m-d but this is not working its showing this error Parse error: syntax error, unexpected T_STRING in downloadlist.php on line 26
please help me to fix this issue
thanks
$filename = Y-m-d " Backup.zip"; (not working)
$filename = time() ." Backup.zip"; ( working code)
downloadlist.php
<?php
// function download($file) downloads file provided in $file
function download($file) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($file));
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($file));
ob_clean();
flush();
readfile($file);
exit;
}
$files = $_POST['file'];
if(empty($files))
{
echo("You haven't selected any file to download.");
}
else
{
$zip = new ZipArchive();
$filename = time() ." Backup.zip"; //adds timestamp to zip archive so every file has unique filename
if ($zip->open($filename, ZIPARCHIVE::CREATE)!==TRUE) { // creates new zip archive
exit("Cannot open <$filename>\n");
}
$N = count($files);
for($i=0; $i < $N; $i++)
{
$zip->addFile($files[$i], $files[$i]); //add files to archive
}
$numFiles = $zip->numFiles;
$zip->close();
$time = 8; //how long in seconds do we wait for files to be archived.
$found = false;
for($i=0; $i<$time; $i++){
if($numFiles == $N){ // check if number of files in zip archive equals number of checked files
download($filename);
$found = true;
break;
}
sleep(1); // if not found wait one second before continue looping
}
if($found) { }
else echo "Sorry, this is taking too long";
}
?>
list.php
<?php
function listDir($dirName)
{
$forbidden_files=array('.htaccess','.htpasswd');
$allow_ext=array('.pdf','.doc','.docx','.xls','.xlsx','.txt');
?><form name="filelist" action="downloadList.php" method="POST"><?php echo "\n";
if ($handle = opendir($dirName)) {
while (false !== ($file = readdir($handle)) ) {
$allowed=(strpos($file,'.')!==false && in_array(substr($file,strpos($file,'.')) ,$allow_ext ));
if ($file != "." && $file != ".." && $allowed ) { ?> <input type=checkbox name="file[]" value="<?php echo "$file";?>"><?php echo "$file"; ?><br><?php echo "\n";
}
}
closedir($handle);
}
?><br><input type="submit" name="formSubmit" value="Zip and download" /></form><?php
}
listDir('.'); ?>
$filename = Y-m-d " Backup.zip"; (not working)
because you are not using date() here. Also, you are not concatenating strings using ..
$filename = date('Y-m-d')."Backup.zip";
The above code will work for you.