how to archive download multiple files from database in php - php

Actually i got the zipfile. But i did't need total files from the table.i want to selected userid files... I try to code bellow, i used php and mysql.
<?php
function zipFilesAndDownload($file_names,$archive_file_name,$file_path)
{
$zip = new ZipArchive();
if ($zip->open($archive_file_name, ZIPARCHIVE::CREATE )!==TRUE) {
exit("cannot open <$archive_file_name>\n");
}
foreach($file_names as $files)
{
$zip->addFile($file_path.$files,$files);
//echo $file_path.$files,$files."<br />";
}
$zip->close();
header("Content-type: application/zip");
header("Content-Disposition: attachment; filename=$archive_file_name");
header("Pragma: no-cache");
header("Expires: 0");
readfile("$archive_file_name");
exit;
}
require_once("config.php");
$cqurfetch=mysql_query("SELECT * FROM albums where user_id='$user_id' and accept='1'");
while($row = mysql_fetch_array($cqurfetch))
{
$file_names[] = $row['user_album_images'];
}
$archive_file_name=time().'.gallery.zip';
$file_path="/uploads/";
zipFilesAndDownload($file_names,$archive_file_name,$file_path);
?>

After Many trails i have got one answer for your question.
Only 'user_id' files are zipped and stored in that zip folder.
Example:-
<?php
require_once("config.php");
$user_id = 49 ; //Just For your reference
$accept = 1 ; //Just For your reference
$sql = "SELECT * FROM albums where user_id='$user_id' and accept='$accept'";
$result = $con->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$array[] = $row["user_album_images"];
echo "user_album_images: " .$row["user_album_images"]. "<br>"; //This is also just for your reference
}
}
else{
echo "fail";
}
$file= "/uploads/gallery.zip"; //Zip file path
$zip = new ZipArchive;
echo "*****zip started.*****\n";
if ($zip->open($file, ZipArchive::CREATE) === TRUE) {
foreach($array as $key => $value)
{
$zip->addFile("/".$value);
}
$zip->close();
echo '^^^^^^Zip ended^^^^^^';
}
?>
I have tested this code in my local system,this is working as like your requirement.
Hope this helps

Related

php can't open pdf after downloading

in my project I need to upload pdf file and download it afterwards.
everything works fine , but after i download the pdf file its been currupted and i can't view it.
if i try to open it with Adobe Acrobat Reader i get this error that says the file been currupted and didn't encoded correctly.
can someone help me to resolve this? thanks!
php script for download and upload:
<?php
// connect to the database
require_once 'connectionoop.php';
require_once 'core/init.php';
$query1 = sprintf("SELECT files.id, files.name,files.size ,files.downloads , association.Aname ,projects.Pname,files.project
FROM files
INNER JOIN projects ON files.project = projects.id INNER JOIN association ON projects.Aid = association.id
");
$result1 = $mysqli->query($query1);
$files=array();
foreach ($result1 as $row) {
$files[] = $row;
}
// Uploads files
if (isset($_POST['save'])) { // if save button on the form is clicked
// name of the uploaded file
$filename = $_FILES['myfile']['name'];
$proj = $_POST['Aid'];
// destination of the file on the server
$destination = 'uploads/' . $filename;
// get the file extension
$extension = pathinfo($filename, PATHINFO_EXTENSION);
// the physical file on a temporary uploads directory on the server
$file = $_FILES['myfile']['tmp_name'];
$size = $_FILES['myfile']['size'];
if (!in_array($extension, ['zip', 'pdf', 'docx'])) {
echo "You file extension must be .zip, .pdf or .docx";
} elseif ($_FILES['myfile']['size'] > 1000000) { // file shouldn't be larger than 1Megabyte
echo "File too large!";
} else {
// move the uploaded (temporary) file to the specified destination
if (copy($file, $destination)) {
$query = sprintf("INSERT INTO files (name, size, downloads , project) VALUES ('$filename', $size, 0,$proj)");
//execute query
$result = $mysqli->query($query);
$sql = "INSERT INTO files (name, size, downloads) VALUES ('$filename', $size, 0)";
$pr=new Project($proj);
$pr->update(array(
'hasfile' =>1
));
Redirect::to('downloads.php');
} else {
echo "Failed to upload file.<br>".$destination;
}
}
}
if (isset($_GET['file_id'])) {
$id = $_GET['file_id'];
$query2 = sprintf("SELECT * FROM files WHERE id=$id");
// fetch file to download from database
$result2 = $mysqli->query($query2);
$data = array();
foreach ($result2 as $row) {
$data[] = $row;
}
$filepath = 'uploads/' .$data[0]['name'];
if (file_exists($filepath)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=' . basename($filepath));
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize('uploads/' . $data['name']));
readfile('uploads/' . $data['name']);
// Now update downloads count
$newCount = $data['downloads'] + 1;
$query3 = sprintf("UPDATE files SET downloads=$newCount WHERE id=$id");
// fetch file to download from database
$result3 = $mysqli->query($query3);
exit;
}
}
It should be header("Content-type:application/pdf");

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";
}

Create zip from array list of elements, stored in different folders

I got a loop with whom I write data in a table, included urls of files I've to zip.
During the loop I put the url in an array.
At the end of table I would have a button, giving me the zip of all files.
I'm in a wordpress site, PHP 5 and Linux.
During loop I save url file here with its path
if (file_exists($file_letttut)) {
$nameAndCode['zipp'] = "http://mypath/to/".$file_letttut;
$namesArray[] = $nameAndCode;}
I tried different codes to zip, I write here the easier
$zip = new ZipArchive;
$zip_name = "zippot.zip"; // Zip name
$res = $zip->open($zip_name, ZipArchive::CREATE);
if ($res === TRUE) {
foreach($namesArray as $key => $value) {
$nomefile = basename($namesArray[$key][zipp].$value);
$nomefile = str_replace('Array', '', $nomefile);
$nomecompleto = str_replace('Array', '', $namesArray[$key][zipp].$value);
$zip->addFile($nomecompleto, $nomefile);
}
$zip->close();
echo 'ok';
} else {
echo 'failed';
}
if(file_exists($zip_name)) {
echo "yes";die;
header('Content-type: application/zip');
header('Content-Disposition: attachment; filename="'.$res.'"');
readfile($res);
unlink($res);
} else {
echo "zip not created";die;
}
$zip_name doesn't exist...
Where do I fail?
Should I've to copy files to a folder before?
Thanks in advance

How can I remove duplicates and add a new unique file?

I have on my website to grab 5 random files from all the files in my directory and all is going well but about %50 of the time I get a duplicate. I would like to:
1) Remove duplicate
2) Replace with new unique file
.. or maybe I can prevent duplicates in an easier manner all together? I tried to find a function for this without asking a question of here but I have not found one. Any ideas? Thanks!!
<?php
//define stuff
$dir = "uploads/";
$allfiles = array_diff(scandir($dir), array('.', '..'));
echo '<pre>';
print_r("all files ready for access");
echo '<pre>';
// create zip
$zip = new ZipArchive();
$zip_name = "zipfile.zip";
if($zip->open($zip_name, ZIPARCHIVE::CREATE)!==TRUE){
$error .= "* Sorry ZIP creation failed at this time";
}
else {
echo '<pre>';
print("created zip");
echo '<pre>';
}
// array of random files
$n=1;
while ($n<=6){
$n ++;
$file = array_rand($allfiles);
$randomfile = $allfiles[$file];
echo '<pre>';
print_r($randomfile);
echo '<pre>';
if (file_exists($dir.$randomfile)) {
$content = $dir.$randomfile;
echo '<pre>';
print_r($content);
echo '<pre>';
$zip->addfile($content,$randomfile);
echo 'ok';
} else {
echo 'failed';
}
}
//present for download
$zip->close();
ob_get_clean();
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=" . basename($zip_name) . ";" );
header("Content-Transfer-Encoding: binary");
header("Content-Length: " . filesize($zip_name));
readfile($zip_name);
if(file_exists($zip_name))
{
unlink('zipfile.zip');
}
?>
Just check if you already found this file. And if you already found it, get a new one by continuing without incrementing $n.
Look at this:
// array of random files
$n = 1;
$myfiles = [];
while ($n<=6){
$file = array_rand($allfiles);
$randomfile = $allfiles[$file];
if(!in_array($randomfile, $myfiles)) { // this line checks if you already got this file
$myfiles[] = $randomfile;
} else {
continue; // if you already got it, continue (http://php.net/manual/de/control-structures.continue.php)
}
echo '<pre>';
print_r($randomfile);
echo '<pre>';
if (file_exists($dir.$randomfile)) {
$content = $dir.$randomfile;
echo '<pre>';
print_r($content);
echo '<pre>';
$zip->addfile($content,$randomfile);
echo 'ok';
} else {
echo 'failed';
}
$n++; // increment in the end
}
You can pass a second parameter to the array_randfunction:
$my_files = array_rand($allfiles, 5);
or shuffle the array and get -for example- the first five items:
shuffle($allfiles);
// now $allfiles[0...4] are 5 different files.
create a an array for the files already added to the zip :
$added = //array
$zip->addfile($content,$randomfile);
array_push($added,$randomfile)
and check any new file in the above array before inserting:
if(!in_array($randomfile, $added)){
//add the file to zip
}

Adding an image to ZipArchive from mysql blob database

I have recently discovered ZipArchive for PHP, i have no problem adding files or files from strings however i have an image blob inside a MySQL database that i want to add to the ZipArchive. I can get the image in a separate file and i can also get it to download as a jpg. I want to be able to add the image into the archive.
The below code shows how i access my BLOB
header('Content-Type: image/jpg; charset=utf-8');
// create a file pointer connected to the output stream
$output = fopen('php://output', 'w');
$conB = mysql_connect("localhost", "user_name", "user_pass");//connect to the database
if (!$conB)
{
die('Could not connect: ' . mysql_error()); // if cannot connect then send error message
}
mysql_select_db("binary", $conB); // define database name
$id = $_GET['ids'];
$query = mysql_query("SELECT * FROM tbl_images WHERE ID ='".$id."' ");
while($row = mysql_fetch_array($query))
{
$content = $row['image'];
header('Content-Disposition: attachment; filename=image"'.$row['ID'].'".jpg');
fwrite($output, $content);
}
That all works fine for me, the below code shows how i am adding a file to a zip archive
$zip = new ZipArchive();
$ZipFileName = "newZipFile.zip";
if ($zip->open($ZipFileName, ZIPARCHIVE::CREATE | ZIPARCHIVE::OVERWRITE) !== true)
{
echo "Cannot Open for writing";
}
$zip->addEmptyDir('newFolder');
$zip->addFromString('text.txt', 'text file');
$zip->close();
//then send the headers to foce download the zip file
header("Content-type: application/zip");
header("Content-Disposition: attachment; filename=$ZipFileName");
header("Pragma: no-cache");
header("Expires: 0");
readfile($ZipFileName);
Does any one know how i can implement them together?
If you need any more information then i can provide it :)
You can create the ZipArchive and then add the image(s) from a loop using addFromString() method. I use snippet from both your source codes below. The database connection logic is left out for simplicity reasons.
$zip = new ZipArchive();
$ZipFileName = "newZipFile.zip";
if ($zip->open($ZipFileName, ZIPARCHIVE::CREATE | ZIPARCHIVE::OVERWRITE) !== true)
{
echo "Cannot Open for writing";
}
$zip->addEmptyDir('newFolder');
$query = mysql_query("SELECT * FROM tbl_images WHERE ID ='".$id."' ");
while($row = mysql_fetch_array($query))
{
$zip->addFromString( $row['image_name'], $row['image']);
}
$zip->close();

Categories