i have some question to tell , how can i download zip and rename the files inside the zip with some php codes ? here is my code :
$file_path='../../files_pangkat/';
$file_names[0] = $ck_sk_terakhir[file_pangkat];
$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
$zip->addFile($file_path.$file_names[0],$file_names[0]);
$zip->renameName($file_names[0], 'SK_PNS_'.$c_bio[nip_baru].'pdf');
echo $file_path.$file_names[0],$file_names[0]."<br />";
$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("Pragma: no-cache");
header("Expires: 0");
readfile("$archive_file_name");
unlink("$archive_file_name");
exit;
$file_names was the name of file that i saved on my database , but when i use $zip->renameName() , it doesn't work ..
It doesn't seem to make a lot of sense to first add a file to the zip file and then rename the newly added file right after that.
Instead, you should add the file with the name you want it to have, also see the manual on addFile().
So you should change:
$zip->addFile($file_path.$file_names[0],$file_names[0]);
$zip->renameName($file_names[0], 'SK_PNS_'.$c_bio[nip_baru].'pdf');
to:
$zip->addFile($file_path . $file_names[0], 'SK_PNS_' . $c_bio[nip_baru] . 'pdf');
Zip creates a lock on the file..you cant rename on the fly ,close it and rename again.
Try it.
$zip->addFile('.....');
....
$zip->close();
$zip->renameName($file_names[0], 'SK_PNS_'.$c_bio[nip_baru].'pdf');
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 have a question
I have looked all over stacked overflow, on how to make a zip out of multiple files, and I got this code:
<?php
$data = $_POST['data'];
$zip = new ZipArchive();
$zip_name = dirname(__FILE__)."/billeder.zip"; // Zip name
$zip->open($zip_name, ZipArchive::CREATE);
foreach ($data as $file) {
$path = dirname(__FILE__)."/".$file;
$zip->addFromString(basename($path), file_get_contents($path));
}
$zip->close();
header('Content-Type: application/zip');
header('Content-disposition: attachment; filename='.basename($zip_name));
header('Content-Length: ' . filesize($zip_name));
ob_clean();
flush();
readfile($zip_name);
unlink($zip_name);
?>
the post data look something like this:
["Billede_008.JPG","Billede_011.JPG"]
a list of images.
My problem is that, I don't receive the zip file, when posting to the url.
I have checked that it got the post data, I've checked that all files in the post exists, and I have checked that the files were added to the zip.
here is the response from chrome. as you can see there's nothing wrong with the response, but I still don't get the zip.
Can anyone see, what I'm doing wrong?
I am getting a base64 binary encoded data from an API request response. I need to save it as zip file. I use the code like below.
<?php
$zipStr = 'UEsDBBQACAAIABprdEEAAAAAAAAAAAAAAAAWAAAAb2JqZWN0cy9Db250YWN0Lm9iamVjdI2SX0vDMBTF3/cpSt9NOhERyTJCl+Gga6VNBZ9GlmWuI21mk0799ka7P50TXR4C9+R3L5ecg4bvpfK2sjaFrgZ+HwS+JyuhF0X1MvBzNr6684e4h8LGWF0m87UU1nMtlRn4K2s39xAazTfALHUtJBC6hNdBcAuDG1hKyxfcch/3PHeQKox9KuSbaetvbdkoFfNSYqEry4WdpXxdzBE86EdUaNWUlcHjPIpmMZlSBPfSOUTCMMljBv7jwiRmJGSATVh0Efj4kMS0fwlJp2QS/Q2mFOQZTTNAognJfmOXhbKyzoTeSEydSx925Yxx/9PRf9Kd/p0q1eKwVphSwuhoNnL315yvt1Pezay5dXHAShqT1PS14QrBo3yKb7lqJGbJiDwj2BbHjeDZSkjxuVR7v72d363Y5gR2goJgN3i49wlQSwcI3kTEMT8BAACvAgAAUEsDBBQACAAIABprdEEAAAAAAAAAAAAAAAALAAAAcGFja2FnZS54bWxNj00LwjAMhu/7FaN3lzpkiHTdQfDkQUS9StbFWbXtWIsf/96xDzSX5CF53ySieJtH/KTWa2dzNk84i8kqV2lb5+x42MyWrJCR2KG6Y01xN219zq4hNCsA77BJ/MW1ihLlDKScZ8AXYChghQGZjOIuRPg05Ie6Z0Om7FbKtbMBVei0fT7v8aZLAVP7J7BoSG61DydNLwE9Dtbw5y3GP2SaJVzARJGA8XwZfQFQSwcIaf0pNKsAAADwAAAAUEsBAhQAFAAIAAgAGmt0Qd5ExDE/AQAArwIAABYAAAAAAAAAAAAAAAAAAAAAAG9iamVjdHMvQ29udGFjdC5vYmplY3RQSwECFAAUAAgACAAaa3RBaf0pNKsAAADwAAAACwAAAAAAAAAAAAAAAACDAQAAcGFja2FnZS54bWxQSwUGAAAAAAIAAgB9AAAAZwIAAAAA';
header('Content-Type: application/zip');
header('Content-disposition: filename="my.zip"');
$out = base64_decode($zipFileValue);
print($out);
?>
But I am getting a SFX zip Archive as downloadable option. which I can`t able to unzip using PHP. I can unzip other normal zip file but not this SFX zip.
Can anybody help me to save the encoded data as zip or tell me how to unzip a SFX zip archive.
You need to create a temporary file for the zip archive, then use ZipArchive() to add your string to the archive as a file. Try the example below.
<?php
$zipStr = 'UEsDBBQACAAIABprdEEAAAAAAAAAAAAAAAAWAAAAb2JqZWN0cy9Db250YWN0Lm9iamVjdI2SX0vDMBTF3/cpSt9NOhERyTJCl+Gga6VNBZ9GlmWuI21mk0799ka7P50TXR4C9+R3L5ecg4bvpfK2sjaFrgZ+HwS+JyuhF0X1MvBzNr6684e4h8LGWF0m87UU1nMtlRn4K2s39xAazTfALHUtJBC6hNdBcAuDG1hKyxfcch/3PHeQKox9KuSbaetvbdkoFfNSYqEry4WdpXxdzBE86EdUaNWUlcHjPIpmMZlSBPfSOUTCMMljBv7jwiRmJGSATVh0Efj4kMS0fwlJp2QS/Q2mFOQZTTNAognJfmOXhbKyzoTeSEydSx925Yxx/9PRf9Kd/p0q1eKwVphSwuhoNnL315yvt1Pezay5dXHAShqT1PS14QrBo3yKb7lqJGbJiDwj2BbHjeDZSkjxuVR7v72d363Y5gR2goJgN3i49wlQSwcI3kTEMT8BAACvAgAAUEsDBBQACAAIABprdEEAAAAAAAAAAAAAAAALAAAAcGFja2FnZS54bWxNj00LwjAMhu/7FaN3lzpkiHTdQfDkQUS9StbFWbXtWIsf/96xDzSX5CF53ySieJtH/KTWa2dzNk84i8kqV2lb5+x42MyWrJCR2KG6Y01xN219zq4hNCsA77BJ/MW1ihLlDKScZ8AXYChghQGZjOIuRPg05Ie6Z0Om7FbKtbMBVei0fT7v8aZLAVP7J7BoSG61DydNLwE9Dtbw5y3GP2SaJVzARJGA8XwZfQFQSwcIaf0pNKsAAADwAAAAUEsBAhQAFAAIAAgAGmt0Qd5ExDE/AQAArwIAABYAAAAAAAAAAAAAAAAAAAAAAG9iamVjdHMvQ29udGFjdC5vYmplY3RQSwECFAAUAAgACAAaa3RBaf0pNKsAAADwAAAACwAAAAAAAAAAAAAAAACDAQAAcGFja2FnZS54bWxQSwUGAAAAAAIAAgB9AAAAZwIAAAAA';
// Prepare Tmp File for Zip archive
$file = tempnam("tmp", "zip");
$zip = new ZipArchive();
$zip->open($file, ZipArchive::OVERWRITE);
// Add contents
$zip->addFromString('your_file_name', base64_decode($zipStr));
// Close and send to users
$zip->close();
header('Content-Type: application/zip');
header('Content-Length: ' . filesize($file));
header('Content-Disposition: attachment; filename="file.zip"');
readfile($file);
unlink($file);
I tried the below way and it worked, nice and easy.
$folderPath = "/this is your folder path to save the zip file/";
$zipStr = "UEsDBBQACAAIABprd_etc";
$zip_Array = explode(";base64,", $zipStr);
$zip_contents = base64_decode($zip_Array[1]);
$file = $folderPath . uniqid() . '.zip';
file_put_contents($file, $zip_contents);
I have the following zip download function:
$file='myStuff.zip';
function downloadZip($file){
$file=$_SERVER["DOCUMENT_ROOT"].'/uploads/'.$file;
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-Transfer-Encoding: Binary");
header("Content-Length: ".filesize($file));
header("Content-Disposition: attachment; filename=\"".basename($file)."\"");
readfile($file);
exit;
}
}
}
The problem is when I call this function, I end up downloading not just myStuff.zip, but the complete directory path with all the folders. I'm on a Mac using XAMPP so this means I get the following:
/applications/xampp/htdocs/uploads/myStuff.zip
meaning i get a folder called applications with all the subfolders and then inside all of them I get myStuff.zip.
How can I just download myStuff.zip without its directories?
Try this.
readfile(basename($file));
Ok, I answered my own question by using the code in this link: http://www.travisberry.com/2010/09/use-php-to-zip-folders-for-download/
Here's the PHP:
<?php
//Get the directory to zip
$filename_no_ext= $_GET['directtozip'];
// we deliver a zip file
header("Content-Type: archive/zip");
// filename for the browser to save the zip file
header("Content-Disposition: attachment; filename=$filename_no_ext".".zip");
// get a tmp name for the .zip
$tmp_zip = tempnam ("tmp", "tempname") . ".zip";
//change directory so the zip file doesnt have a tree structure in it.
chdir('user_uploads/'.$_GET['directtozip']);
// zip the stuff (dir and all in there) into the tmp_zip file
exec('zip '.$tmp_zip.' *');
// calc the length of the zip. it is needed for the progress bar of the browser
$filesize = filesize($tmp_zip);
header("Content-Length: $filesize");
// deliver the zip file
$fp = fopen("$tmp_zip","r");
echo fpassthru($fp);
// clean up the tmp zip file
unlink($tmp_zip);
?>
and the HTML:
Download All As Zip
The key step in getting rid of the directory structure appears to be the chdir(). It is also worth noting that the script in this answer makes the zip file on the fly rather than trying to retrieve a previously zipped file as I did in my question.
As per php manual I have already enable php_zip.dll in the php.ini file and also check php_zip.dll in ext folder of php installation folders. It appears there. But While using code for zip it shows errors as below:
Fatal error: Class 'ZipArchive' not found in C:\inetpub\wwwroot\projectname\bulkdownload.php on line 9
Following is the code of bulk download.php
<?php
function zipFilesAndDownload($file_names,$archive_file_name,$file_path)
{
$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,$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("Pragma: no-cache");
header("Expires: 0");
readfile("$archive_file_name");
exit;
}
$file_array = $_GET['voice'];
$file_names = explode(';', $file_array);
$archive_file_name = "voicefile.zip";
$file_path = "d:/temp_file/voice/";
zipFilesAndDownload($file_names,$archive_file_name,$file_path);
?>
Run phpinfo().
Above the "zlib" heading, see if there is a "zip" heading. If not then the zip module has not been installed correctly. If so check that it is "enabled".