Hi i am making a download feature on my website and it is running however all the files are corrupted due to a recurring error readfile(): Filename cannot be empty in 'my/file/location' I don't understand why this is happening because according to every post I have looked at I am doing the download->zipfiles procedure correctly. Please help.
By the way i think the key to the answer may be in the fact that when i open the zip in a text file it reads:
Warning: file_get_contents(/uploads/): failed to open stream: No such file or directory in /home/ghostx19/public_html/phDownloader.php on line 21
the error is repeated 10 times because of the loop obviously
My Code:
<?php
//define stuff
$dir = "./uploads";
$allfiles = glob($dir.'*.{aiff}', GLOB_BRACE);
// 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";
}
//array of random files
$n=1;
while ($n<=10){
$n ++;
$randomfile = $allfiles[array_rand($allfiles)];
$path = "./uploads".$randomfile;
$zip->addFile(basename($path), file_get_contents($path));
}
// //present for download
$zip->close();
header('Content-Type: application/zip');
header('Content-disposition: attachment; filename='.$zip_name);
readfile('zipfile.zip');
if(file_exists('zipfile.zip'))
{
unlink('zipfile.zip');
}
?>
Related
I have a web service that is requesting for data. The data received is being stored in the variable $response.
After that, i am creating files to store the data.
Then i am trying to add these files to a zip and afterwards download that zip. I have consulted various questions and answers similar to mine but i still cannot solve my problem. Note that i have the zip library installed.
Below is my php script:
// Load zip library
$zip = new ZipArchive();
//Zip name
$zip_name = "data.zip";
if($zip->open($zip_name, ZIPARCHIVE::CREATE)!==TRUE){
// Opening zip file to load files
$error = "ZIP creation failed at this time";
}
else{
echo "zip creation successful";
}
function myFunc(){
//Some codes
global $zip;
$myfile = fopen($filepath, "w");
fwrite($myfile, $response);
fclose($myfile);
echo "test1";
try {
//add file to zip
$zip->addFile($myfile);
}
catch (Exception $e) {
echo $e->getMessage();
}
echo "test2";
}
$zip->close();
//Some codes
if(file_exists($zip_name)){
// push to download the zip
header('Content-type: application/zip');
header('Content-Disposition: attachment; filename="'.$zip_name.'"');
readfile($zip_name);
// remove zip file is exists in temp path
unlink($zip_name);
}
After running the above script, test1 is being displayed and not test2. I think that the problem lies in this line $zip->addFile($myfile);.
From previous posts, i could notice that the function addFile takes 2 parameters. How can i edit my code for this?
Thanks for your help.
I'm able to directly write and read files in Google Storage, but when I try to use ZipArchive to create a file, it fails. Google says that the zip extension is enabled in the GAE.
$tmpdirectory .= 'gs://#default#/tmp/user-'.$uid;
$uniqueid = uniqid() . time();
$user_visible_filename = 'export.zip';
$output_path = sprintf("%s/export.%s.zip", $tmpdirectory, $uniqueid);
$zip = new ZipArchive;
$res = $zip->open($output_path, ZipArchive::CREATE);
if ($res === true) {
foreach ($data as $datatype => $records) {
$filename = sprintf("%s/%s.csv", $tmpdirectory, $datatype);
write_csv_to_filename($records, $filename);
$localname = basename($filename);
$fileresult = $zip->addFromString($localname, file_get_contents($filename));
print "adding $localname... num files in zip: ".($fileresult ? "true" : "false")." -> ".$zip->numFiles."<br/>\n";
}
}
$closeresult = $zip->close();
print "user_visible_filename: $user_visible_filename<br/>\n";
print "zip filename: $output_path<br/>\n";
print "file size: ".filesize($output_path)."<br/>\n";
header('Content-Type: application/zip');
header('Content-Length: '.filesize($output_path));
header('Content-Disposition: attachment; filename=' . $user_visible_filename);
The above code writes some csv files and I want to bundle them together in a zip file and have their browser download it. I know that the above headers() won't work because I'm printing stuff about before them; I'm going printing the stuff out to debug what's going wrong.
I am able to write each of the CSVs to gs:// and I'm able to access their correct filesize and read their contents back after writing them.
However, when I try to read the filesize() of the zip file (gs://#default#/tmp/user-152/export.5b4565bda18481531274685.zip) it craps out with a big warning message (cannot stat file) and stack trace as if the file doesn't exist.
$zip->close(); returns false which means there was a failure, but I have no idea why it failed.
I found an alternative solution that worked: TbsZip
require_once '../inc/tbszip.php';
$tmpfile = tempnam('/tmp', 'export');
$zip = new clsTbsZip();
$zip->CreateNew($tmpfile);
foreach ($data as $datatype => $records) {
$filename = sprintf("%s/%s.csv", $tmpdirectory, $datatype);
write_csv_to_filename($records, $filename);
$localname = basename($filename);
//$fileresult = $zip->addFile($filename, $localname);
$zip->FileAdd($localname, file_get_contents($filename), TBSZIP_STRING);
}
// Flush() will send all the required headers for downloading the file.
$zip->Flush(TBSZIP_DOWNLOAD, $user_visible_filename, 'application/zip');
$zip->Close();
Am developing a code that creates a ZIP file out of selected files from a folder. The folder is created with sessiontime as name, but the files are not added to the ZIP file. The permissions of files are 777. The files are getting selected, indicated by the output below. I have also checked the code by replacing with line $zip->addFile($file_folder); which downloads a blank zip archive, hence there is no issue with it.
<?php
ob_start();
$error = ""; //error holder
if(isset($_POST['createpdf']))
{
$post = $_POST;
$file_folder = "test/".$_SESSION["dir_name"]."/"; // folder to load files
echo $file_folder;
if(extension_loaded('zip'))
{ // Checking ZIP extension is available
echo "checking";
if(isset($post['files']) and count($post['files']) > 0)
{ echo "/checking2";// Checking files are selected
$zip = new ZipArchive(); // Load zip library
$zip_name = time().".zip"; // Zip name
if($zip->open($zip_name, ZIPARCHIVE::CREATE)!==TRUE)
{
// Opening zip file to load files
echo "* Sorry ZIP creation failed at this time<br/>";
}
foreach($post['files'] as $file)
{ echo "added";
$zip->addFile($file_folder.$file); // Adding files
into zip
}
$zip->close();
if(file_exists($zip_name))
{
// push to download the zip
header('Content-type: application/zip');
header('Content-Disposition: attachment; filename="'.$zip_name.'"');
readfile($zip_name);
// remove zip file is exists in temp path
unlink($zip_name);
The output I get is the line : test//checking/checking2addedaddedadded
You forgot session_start() after opening the <?php tag, so your $_SESSION['dir_name'] variable is empty
<?php
$error = "";
$file_folder = "temp/";
// folder to load files
if (extension_loaded('zip')) {
// Checking ZIP extension is available
$zip = new ZipArchive();
// Load zip library
$zip_name = "images_".date("d-m-Y") . ".zip";
// Zip name
if ($zip -> open($zip_name, ZIPARCHIVE::CREATE) !== TRUE) {
// Opening zip file to load files
$error .= "* Sorry ZIP creation failed at this time";
}
$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator("../uploads/"));
$files = iterator_to_array($iterator, true);
foreach ($iterator as $file) {
$zip -> addFile($file_folder . $file);
// Adding files into zip
}
print_r($zip);
//echo $zip_name;
if (file_exists($file_folder.$zip_name)) {
// push to download the zip
header('Content-type: application/zip');
header('Content-Disposition: attachment; filename="' . $zip_name . '"');
readfile($zip_name);
// remove zip file is exists in temp path
unlink($zip_name);
} else {
echo "error";
}
$zip -> close();
//} else
// $error .= "* Please select file to zip ";
} else
$error .= "* You dont have ZIP extension";
?>
I have tried outputting $zip object and got following response:
ZipArchive Object ( [status] => 0 [statusSys] => 0 [numFiles] => 12 [filename] => /var/www/bigb/ajax/images_24-12-2012.zip [comment] => )
Status Zero explains there were no errors while creating zip (reference: http://www.php.net/manual/en/zip.constants.php)
I have referred posts:
1) Download all images from a single directory of a website
2) How to create a zip file using php and delete it after user downloads it?
3) http://www.9lessons.info/2012/06/creating-zip-file-with-php.html
Third one helped me the most and in the other 2 i was getting status as 23.
Issue: I am able to create a zip & no issue downloading it but when i open the zip i don't see any files inside but zip has memory in mbs.
Please Help me out...
Update: Error 23 occurs because of print_r / echo and or trying to overwrite same file.
Update2: Issue solved. It was due to path in RecursiveDirectoryIterator (i.e ../uploads/) once i moved the code to main folder and changed the path to (uploads/) everything started working as it should be. Kudos!!!
It was due to path in RecursiveDirectoryIterator (i.e ../uploads/) once i moved the code to main folder and changed the path to (uploads/) everything started working as it should be. Kudos!!!
I think the file path you are providing to $zip->addFile() is incorrect. You don't need to append anything to $file. Following will work:
foreach ($iterator as $file) {
$zip -> addFile($file);
}
In your case the $file will contain exact relative path of file like ../uploads/file.ext.
I'm trying to download multiple files in a zip archive using PHP/codeigniter.This code works on my localhost but on the webhost the zip starts download but the files are not added to the zip file. This is the error I got:
A PHP Error was encountered
Severity: Warning
Message: readfile(Album1.zip): failed to open stream: No such file or directory
Filename: controllers/download.php
Line Number: 54
This is my code:
function _zipFilesAndDownload($file_names,$archive_file_name,$file_path)
{
$zip = new ZipArchive();
if(file_exists($archive_file_name)){
if ($zip->open($archive_file_name, ZIPARCHIVE::OVERWRITE )!==TRUE) {
exit("cannot open <$archive_file_name>\n");
}
}else
//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);
//echo $file_path.$files."<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");
exit;
}
function album($albumid){
$this->load->model("albums_model");
$this->load->model("songs_model");
$aid = $albumid;
$albuminfo = $this->albums_model->getAlbum($aid);
$songs = $this->songs_model->getSongNamesAvailableDownload($aid);
$file_path=$_SERVER['DOCUMENT_ROOT']. '/demo/albums/'.$albumid.'/';
$archive_file_name = $albuminfo->album_name;
$file_names = $songs;
$this->_zipFilesAndDownload($file_names,$archive_file_name,$file_path);
}
CodeIgniter provides a zip library for this purpose. It's a lot easier to handle and you can reduce your code to a minimum. This might also solve your problem. Good luck!