Hi I am trying to collect a number of random files from a folder on my server (./uploads) and zip them so the user can download. I think I am pretty close but I could use some help. I am getting a "503 backend fetch" error everytime and i can not pinpoint my issue. Thank you!!!
<?php
$rootPath = realpath('./uploads');
//make zip file
$zip = new ZipArchive();
$zip->open('file.zip', ZipArchive::CREATE | ZipArchive::OVERWRITE);
$nfiles = glob($rootPath.'*.{aiff}', GLOB_BRACE);
$files = $nfiles[array_rand($nfiles,20)];
//-------------------------------------------//
foreach ($files as $file)
{
if (!$file->isDir())
{
// Get path for current file
$filePath = $file->getRealPath();
$relativePath = substr($filePath, strlen($rootPath) + 1);
// Add file to zip
$zip->addFile($filePath, $relativePath);
}
}
//-------------------------------------------//
$zip->close();
header('Content-Type: application/zip');
header('Content-disposition: attachment; filename='.'generated
sounds.zip');
header('Content-Length: ' . filesize('file.zip'));
readfile('file.zip');
if(file_exists('file.zip')){
unlink('file.zip');
}
?>
Related
1 - I have a folder has a lot of users folder inside it, and every user's folder has others folders inside it has ismages inside them like this:
localhost/cm/app/model/uploads/mark/3/small/car.jpg
localhost/cm/app/model/uploads/mark/3/big/car.jpg
localhost/cm/app/model/uploads/stiven/9/small/pc.jpg
localhost/cm/app/model/uploads/stiven/9/big/pc.jpg
2 - I want that i donwload this folders with all its content.
3 - I prefer that I download it without zipping it with the same name, if it's not possible with zipping it with any name.
4 - I've used this code and it's not working because when I try to open the zip folder after downloading it an error message appear and tell me that "the archive is either unknown format or damaged", and this my code:
<?php
$dir = 'http://localhost/cm/app/model/uploads'; //folder path
$archive = time().'download.zip';
$zip = new ZipArchive;
$zip->open($archive, ZipArchive::CREATE);
$files = scandir($dir);
unset($files[0], $files[1]);
foreach ($files as $file) {
$zip->addFile($dir.'/'.$file);
}
$zip->close();
header('Content-Type: application/zip');
header('Content-disposition: attachment; filename='.$archive);
header('Content-Length: '.filesize($archive));
readfile($archive);
unlink($archive);
?>
*So how to download my folder with all its folders and images without zipping it or with zipping if not possible?
I suspect you've got an error in you're code. maybe ext-zip isn't install one way of checking this is by running php -m in a terminal which will display all install and enabled modules.
If you open up the zip file with a text editor it's like there be an error message instead of archived data.
This is The best way that i found:
<?php
// Get real path for our folder
$rootPath = realpath('folder_for_ziping');
// Initialize archive object
$zip = new ZipArchive();
$zip->open('file.zip', ZipArchive::CREATE | ZipArchive::OVERWRITE);
// Create recursive directory iterator
/** #var SplFileInfo[] $files */
$files = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($rootPath),
RecursiveIteratorIterator::LEAVES_ONLY
);
foreach ($files as $name => $file)
{
// Skip directories (they would be added automatically)
if (!$file->isDir())
{
// Get real and relative path for current file
$filePath = $file->getRealPath();
$relativePath = substr($filePath, strlen($rootPath) + 1);
// Add current file to archive
$zip->addFile($filePath, $relativePath);
}
}
// Zip archive will be created only after closing object
$zip->close();
$archive = "file.zip";
header('Content-Type: application/zip');
header('Content-disposition: attachment; filename='.$archive);
header('Content-Length: '.filesize($archive));
readfile($archive);
unlink($archive);
?>
I am trying to download some images as a zip file to my download folder in pc. But it always downloaded to the projects public folder. What can be the issue?
Here is my code
$photos = json_decode(Input::get('photos'));
$dir = time();
foreach($photos as $file){
$imgName = last(explode('/', $file));
$path = public_path('downloads/'.$dir);
if(!File::exists($path)){
File::makeDirectory($path, 0775, true);
}
ImageHandler::downloadFile($file, $path.'/'.$imgName);
}
$rootPath = realpath($path);
$zip = new ZipArchive();
$file_name = 'photos.zip';
$zip->open( $file_name, ZipArchive::CREATE | ZipArchive::OVERWRITE);
/** #var SplFileInfo[] $files */
$files = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($rootPath),
RecursiveIteratorIterator::LEAVES_ONLY
);
foreach ($files as $name => $file1)
{
// Skip directories (they would be added automatically)
if (!$file1->isDir())
{
// Get real and relative path for current file
$filePath = $file1->getRealPath();
$relativePath = substr($filePath, strlen($rootPath));
// Add current file to archive
$zip->addFile($filePath, $relativePath);
}
}
$zip->close();
header("Content-Type: application/zip");
header("Content-Disposition: attachment; filename=$file_name");
readfile($filePath);
exit;
I want to export all my images in a zip, but for some reason it adds all of my local disk too... I dont understand..
This is the code:
$files = $urls;
$zipname = 'uploads.zip';
$zip = new ZipArchive;
$zip->open($zipname, ZipArchive::CREATE);
foreach ($files as $file) {
$name = explode( '/', $file);
$zip->addFile($file, pathinfo( $file, PATHINFO_BASENAME ));
}
$zip->close();
header('Content-Type: application/zip');
header('Content-disposition: attachment; filename='.$zipname);
header('Content-Length: ' . filesize($zipname));
readfile($zipname);
$files is an array of the location of the image:
ServicesController.php on line 61:
array:3 [▼
0 => "C:\wamp\www\prjct\app/../../prjct/web/uploads/media/default/0001/15/thumb_14794_default_big.gif"
1 => "C:\wamp\www\prjct\app/../../prjct/web/uploads/media/default/0001/15/thumb_14794_default_small.gif"
2 => "C:\wamp\www\prjct\app/../../prjct/web/uploads/media/default/0001/15/thumb_14794_admin.gif"
]
When I opne my zip file i see this:
As you can see there is my local disk witch should not be here..
This should work:
$files = $urls;
$zipname = 'uploads.zip';
$zip = new ZipArchive;
$zip->open($zipname, ZipArchive::CREATE);
$rootPath = realpath($files);
$files = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($rootPath),
RecursiveIteratorIterator::LEAVES_ONLY
);
foreach ($files as $name => $file) {
// Get real and relative path for current file
$filePath = $file->getRealPath();
$relativePath = substr($filePath, strlen($rootPath) + 1);
// non-empty directories would be added automatically
if (!$file->isDir()){
// Add current file to archive
$zip->addFile($filePath, $relativePath);
}
}
$zip->close();
Generally, you should to use DIRECTORY_SEPARATOR predefined constant instead of slashes/back slashes. This is especially helpful when developing on a Windows machine.
Generally, when working on Windows, make sure to remove the trailing slash when adding folders to zip - that is what created the local disk in your zip file.
$localDirNoSlashes = rtrim($localDir, DIRECTORY_SEPARATOR);
$zip->addEmptyDir($localDirNoSlashes);
This was driving me crazy for a while until I realized what is going on...
I am trying to randomly download some files.
I apologize because I posted it earlier but can someone explain what I am doing wrong in detail?
I can not seem to debug it as I know minimal php.
<?php
$rootPath = realpath('./uploads');
//make zip file
$zip = new ZipArchive();
$zip->open('file.zip', ZipArchive::CREATE | ZipArchive::OVERWRITE);
$nfiles = glob($rootPath.'*.{aiff}', GLOB_BRACE);
$files = array_rand($nfiles, 20);
foreach($files as $file) {
$pathtofile = $nfiles[$file];
if (!$file->isDir())
{
// Get path for current file
$filePath = $pathtofile->getRealPath();
$relativePath = str_replace($rootPath, "", $file);
// Add file to zip
$zip->addFile($filePath, $relativePath);
}
}
//-------------------------------------------//
$zip->close();
header('Content-Type: application/zip');
header('Content-disposition: attachment;
filename='.'generatedsounds.zip');
header('Content-Length: ' . filesize('file.zip'));
readfile('file.zip');
if(file_exists('file.zip'))
{
unlink('file.zip');
}
?>
You're calling ->isDir() method which is not defined, And you're calling ->getRealPath() which is also not defined.
And you're getting all files then selecting 20 random files from the array (why??)
While you are rewriting the headers, errors won't be shown in browser, try without rewriting headers which means it's kept as html header and test until you get a binary file output then add the headers back so you have a working code.
I'm trying to create zip files using CakePhp 1.3. The file descriptions are stored in database. In my controller I'm using the following logic.
// Fetching File description form database.
$this->view = 'Media';
$user_id=$this->Session->read('userData.User.id');
$condition = "Document.isdeleted = '0' AND Document.project_id='". $project_id."'";
$projectDocumentList = $this->Document->find("all",array('conditions'=>$condition,'fields'=>array('Document.id','Document.document_name','Document.path'),'order' => array('Document.id ASC')));
$this->set('projectDocumentList',$projectDocumentList);
if(!empty($projectDocumentList)){
$fileNames = "";
$fileNamesArr = array();
foreach($projectDocumentList as $projectDocument){
$fileNamesArr[ ]= $projectDocument['Document']['document_name'];
}
}
// Making zip
$archive_file_name='myFile.zip';
$file_path= "my_file_path";// Here I'm using my server basepath
$zip = new ZipArchive();
if ($zip->open($archive_file_name, ZIPARCHIVE::CREATE )!==TRUE) {
exit("cannot open <$archive_file_name>\n");
}
foreach($fileNamesArr as $files)
{
$zip->addFile($file_path.$files,$files);
//echo $file_path.$files."<br>"; // This can show the file in browser
}
$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;
Now the zip file download as myFile.zip, but when I'm going to open that file, it throws an error "The archive is either in unknown format or damaged".
Create Zip File of whole folder
// Get real path for our folder
$rootPath = realpath('folder-to-zip');
// Initialize archive object
$zip = new ZipArchive();
$zip->open('file.zip', ZipArchive::CREATE | ZipArchive::OVERWRITE);
// Create recursive directory iterator
/** #var SplFileInfo[] $files */
$files = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($rootPath),
RecursiveIteratorIterator::LEAVES_ONLY
);
foreach ($files as $name => $file)
{
// Skip directories (they would be added automatically)
if (!$file->isDir())
{
// Get real and relative path for current file
$filePath = $file->getRealPath();
$relativePath = substr($filePath, strlen($rootPath) + 1);
// Add current file to archive
$zip->addFile($filePath, $relativePath);
}
}
// Zip archive will be created only after closing object
$zip->close();
And than pass the path of the zip file to the view.
$this->set('Zip_path'.zip_file_name);