I managed to zip the files and downloaded it. The only problem is that I cant extract the zip file is says "An error occured while loading the archive". It contains data since it has around 1000kb. Is there something wrong with my code?
$zip = new ZipArchive();
$zip_name = "zipfile.zip";
if($zip->open($zip_name, ZipArchive::CREATE) !== TRUE) {
echo("Zip failed");
} else {
foreach($temp_file as $file) {
$zip->addFile($file, $file);
}
$zip->close();
header('Content-disposition: attachment; filename=media.zip');
header('Content-type: application/zip');
readfile($zip_name);
}
I've added a variable $zipname to contain the full path to your "zipfile.zip". It is later used to determine the filesize, which is send with the content-length header. Please adjust the path!
added some more headers, especially length and pragma
adjusted length and disposition to use dynamic filenames based on the variables on the top
added exit() after readfile() - rare, but you never know the registered shutdown handlers and their output behaviour
keep in mind, if you have large files you are sending through readfile() and you have a busy site, this will consume memory
Give it a try:
<?
$zip = new ZipArchive();
$zip_name = "/path/to/zipfile.zip"; // <-- adjust path
$file_name = basename($zip_name);
if($zip->open($zip_name, ZipArchive::CREATE) !== TRUE) {
echo("Zip failed");
} else {
foreach($temp_file as $file) {
$zip->addFile($file, $file);
}
$zip->close();
header("Pragma: public");
header("Content-Type: application/zip");
header("Content-Disposition: attachment; filename=$file_name");
header("Content-Length: " . filesize($zip_name));
header("Content-Transfer-Encoding: binary");
readfile($zip_name);
exit;
}
Related
I am attempting to create a zip file that has a simple text file inside. Unfortunatly when I open the zip file, the file is empty, although in the code I have added in a text file.
I have looked for other questions on the topic with no avail and I have tried adding different files such as photos , but the zip is always empty.
How can I succesfully add files to my zip?
Here is the commented code
if($_POST['down']){
ob_clean(); //clean and flush
ob_end_flush();
$zip = new ZipArchive(); //create new zip
$filename = 'images.zip'; //call the zip a name
if($zip->open($filename, ZipArchive::CREATE) == FALSE){ //if zip can't be opened or created, kill the script
die('nozip');
}
$string = 'wef2emfofp32fo2mfomepofm'; // a string
$zip->addFromString('text.txt', $string); //add the string to the zip
$zip->close(); //close zip
header("Content-Disposition: attachment; filename=".basename(str_replace(' ', '_', $filename)));
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/zip");
header("Content-Description: File Transfer");
header("Content-Length: " . filesize($filename));
//download the zip
}
remove these codes
if($zip->open($filename, ZipArchive::CREATE) == FALSE){ //if zip can't be opened or created, kill the script
die('nozip');
}
and surround everything else with a try catch block. You might find answers in the exception message if that block is not itself the cause.
With this simple code (from php documentaion)
I have created succesfully the zip and the content
<?php
$zip = new ZipArchive;
$res = $zip->open('test.zip', ZipArchive::CREATE);
if ($res === TRUE) {
$zip->addFromString('test.txt', 'file content goes here');
$zip->close();
echo 'ok';
} else {
echo 'failed';
}
?>
I had a set of files in a folder. from this few will select and adding to zip. But it adding non selected files also.
The sample file names are
EXPLORER_TRM_FDM_147461_B_280.pdf,
EXPLORER_TRM_FDM_147463_B_130.txt,
EXPLORER_TRM_FDM_147470_B_130.pdf,
From this I am selecting only second one but all are coming.
my function is
public function zipFilesDownload($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.strtolower($files),$files);
}
$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;
}
$file_names contain only
EXPLORER_TRM_FDM_147463_B_130.txt
but the other two also adding into zip. where I am wrong?
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.
I have an array of links to mp3 files. I need to have all of the mp3s downloaded from a server and then zipped.
This code below is not working:
Any suggestions?
$audio_flies = array('http://example.com/1.mp3','http://example.com/2.mp3');
$zipname = 'file.zip';
$zip = new ZipArchive;
$zip->open($zipname, ZipArchive::CREATE);
foreach ($audio_files as $file) {
echo "$file";
$zip->addFile($file);
}
$zip->close();
header('Content-Type: application/zip');
header('Content-disposition: attachment; filename='.$zipname);
header('Content-Length: ' . filesize($zipname));
readfile($zipname);
The archive is either in unknown format or damaged
You first need to download those files and store them locally on your server. Once that is done you will be able to zip them and make the zip file available for download.
The most basic way of achieving this is by using PHP's file_get_contents(), file_put_contents() and parse_url().
This code has not been thoroughly tested.
// Fixed the name of the array
$audio_files = array('http://example.com/1.mp3', 'http://example.com/2.mp3');
// You need to change this to
// a path where you want to store your
// audio files (Absolute path is best)
$local_path = '/local/path/here/';
$zipname = 'file.zip';
$zip = new ZipArchive;
$zip->open($zipname, ZipArchive::CREATE);
// Download the files
// Not an elegant way to
// download files
foreach ($audio_files as $file) {
// First let's get the file name
// by parsing the URL
// and trimming the '/'
$file_name = ltrim(parse_url($file, PHP_URL_PATH), '\/');
// Download the file
$a_contents = file_get_contents($file);
// Place the downloaded content
// in the defined local path
file_put_contents($local_path . $file_name, $a_contents);
// Add the file to archive
$zip->addFile($local_path . $file_name);
}
$zip->close();
header('Content-Type: application/zip');
header('Content-disposition: attachment; filename='.$zipname);
header('Content-Length: ' . filesize($zipname));
readfile($zipname);
This is a very bad way to achieve your task for the following reasons (among many others):
There is no timeout for the download process
If a file fails to download it will halt the execution
It may take a very long time (depending on the size of the audio files) to serve the zip file
There is no proper error / exception handler
Many other reasons regarding structure that I'm not gonna go through here.
try the following: use parse_url to get the actual filename, use file_get_contents and file_put_contents to download and save the data locally...
$audio_flies = array('http://example.com/1.mp3','http://example.com/2.mp3');
$zipname = 'file.zip';
$zip = new ZipArchive;
$zip->open($zipname, ZipArchive::CREATE);
foreach ($audio_files as $file) {
echo "$file";
$parsed = parse_url($file);
$localfile = "." . $parsed["path"];
$mp3 = get_file_contents($file);
file_file_contents($localfile, $mp3);
$zip->addFile($localfile);
}
$zip->close();
header('Content-Type: application/zip');
header('Content-disposition: attachment; filename='.$zipname);
header('Content-Length: ' . filesize($zipname));
readfile($zipname);
<?php
$direc = base64_decode($_GET['path']);
$zip = new ZipArchive();
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, $files);
}
$zip->close();
header('Content-Type: application/octet-stream');
header("Content-Disposition: attachment; filename=" . $archive_file_name);
header('Cache-control: private, must-revalidate');
header('Content-Transfer-Encoding: binary');
readfile("$archive_file_name");
exit;
}
if (isset($_POST['file'])) {
$file_names = $_POST['file'];
$archive_file_name = 'zipped.zip';
$file_path = $direc;
echo $file_path;
//Run Function above
zipFilesAndDownload($file_names, $archive_file_name, $file_path);
if (file_exists($archive_file_name)) {
unlink($archive_file_name);
}
?>
I find code above and try it, The zip file created but statement unlink($zipname); doesn't work
I don't have any problem about permission
Is that file strill write-protected?
How to solve that problem?
Thanks Friends
Your function above should call return, not exit. Exit terminates execution of the script, so nothing after that will be called. It's probably not even getting to the file_exists part.