Delete existing zip file - php

I have a working code which can download all images from a website. I grab all the images, put them in a cache folder, create the zip file and download them. The problem what I can't solve is to delete the zip after I downloaded it. Here is my code:
foreach($image as $im){
$info = explode('/',$im);
$file_name = 'cache/'.$info[count($info)-1];
copy($im,$file_name);
$to_zip[] = $file_name;
}
// Zipping
$result = create_zip($to_zip,'kepek.zip');
// Clear cache
$files = glob('cache/*');
foreach($files as $file) if(is_file($file)) unlink($file);
// Download
Header('Location: kepek.zip');

Use unlink after the header
foreach($image as $im){
$info = explode('/',$im);
$file_name = 'cache/'.$info[count($info)-1];
copy($im,$file_name);
$to_zip[] = $file_name;
}
// Zipping
$result = create_zip($to_zip,'kepek.zip');
// Clear cache
$files = glob('cache/*');
foreach($files as $file) if(is_file($file)) unlink($file);
// Download
Header('Location: kepek.zip');
unlink('Location: kepek.zip');

Related

How to move files to another folder in php

I have 4 csv files in "files" folder & I want to move these files with content to another folder (i.e. backups),Files are given below.
abc.csv
abc1.csv
abc2.csv
$files = scandir('files');
$destination = 'backups/';
$date = date('Y-m-d');
foreach($files as $file){
$rename_file = $file.'_'.$date;
move_uploaded_file($rename_file, "$destination");
}
Since you are not uploading any files, try rename() function instead.
$Ignore = array(".","..","Thumbs.db");
$OriginalFileRoot = "files";
$OriginalFiles = scandir($OriginalFileRoot);
$DestinationRoot = "backups";
# Check to see if "backups" exists
if(!is_dir($DestinationRoot)){
mkdir($DestinationRoot,0777,true);
}
$Date = date('Y-m-d');
foreach($OriginalFiles as $OriginalFile){
if(!in_array($OriginalFile,$Ignore)){
$FileExt = pathinfo($OriginalFileRoot."\\".$OriginalFile, PATHINFO_EXTENSION); // Get the file extension
$Filename = basename($OriginalFile, ".".$FileExt); // Get the filename
$DestinationFile = $DestinationRoot."\\".$Filename.'_'.$Date.".".$FileExt; // Create the destination filename
rename($OriginalFileRoot."\\".$OriginalFile, $DestinationFile); // rename the file
}
}
The function move_uploaded_file is relevant for uploading files, not for other things.
To move file in the filesystem you should use the rename function:
$files = scandir('files');
$destination = 'backups/';
$date = date('Y-m-d');
foreach($files as $file){
if (!is_file($file)) {
continue;
}
$rename_file = $destination.$file.'_'.$date;
rename($file, $rename_file);
}

Download Images with zip File

I am generating dynamic images from API.
And on button click i want to download a zip file with images .
I tried many solution, but still not able to download zip file with images
$zip = new ZipArchive();
$zip_name = time().".zip"; // Zip name
$zip->open($zip_name, ZipArchive::CREATE);
foreach ($files as $file) {
echo $path = "uploadpdf/".$file;
if(file_exists($path)){
$zip->addFromString(basename($path),file_get_contents($path));
}else {
echo"file does not exist";
}
}
$zip->close()

Move or Delete and Force download of Archive after creation

To put it simply, I would like my users to be able to download their website files, so I created a "Download Website" button which uses this script to add all files/folders in their directory which is in the variable $direc and archive those files/folders.
<?
///////// DOWNLOAD ENTIRE WEBSITE:
if(isset($_POST['download_site'])){
// define some basics
$rootPath = '../useraccounts/'.$direc.'';
$archiveName = ''.$direc.'.zip';
// initialize the ZIP archive
$zip = new ZipArchive;
$zip->open($archiveName, ZipArchive::CREATE);
// create recursive directory iterator
$files = new RecursiveIteratorIterator (new RecursiveDirectoryIterator($rootPath), RecursiveIteratorIterator::LEAVES_ONLY);
// let's iterate
foreach ($files as $name => $file) {
$filePath = $file->getRealPath();
$zip->addFile($filePath);
}
// close the zip file
if (!$zip->close()) {
echo '<p>There was a problem writing the ZIP archive.</p>';
} else {
echo '<p>Successfully created the ZIP Archive!</p>';
}
}
?>
To my surprise, this code works. Although, there are a few hiccups:
It doesn't automatically force a download of that archive.
It adds the archive in to my main directory rather than moving it to a separate directory of my choice such as site_downloads or deletes it up on completed download.
Are these problems at all fixable or if not, is there a better way to do it so my main directory does not get filled with constant downloads? I guess it will cause a problem once a Archive is created more than once, as it uses the Directory name.
Solved this by using a few different combinations:
<?
///////// DOWNLOAD ENTIRE WEBSITE:
if(isset($_POST['download_site'])){
// define some basics
$rootPath = '../useraccounts/'.$direc.'';
$archiveName = ''.$direc.'.zip';
// initialize the ZIP archive
$zip = new ZipArchive;
$zip->open($archiveName, ZipArchive::CREATE);
// create recursive directory iterator
$files = new RecursiveIteratorIterator (new RecursiveDirectoryIterator($rootPath), RecursiveIteratorIterator::LEAVES_ONLY);
// let's iterate
foreach ($files as $name => $file) {
$filePath = $file->getRealPath();
$zip->addFile($filePath);
}
// close the zip file
if (!$zip->close()) {
echo '<p>There was a problem writing the ZIP archive.</p>';
} else {
rename($archiveName, 'user_archives/'.$archiveName.'');
$yourfile = "user_archives/".$archiveName."";
$file_name = basename($yourfile);
header("Content-Type: application/zip");
header("Content-Disposition: attachment; filename=$file_name");
header("Content-Length: " . filesize($yourfile));
readfile($yourfile);
ignore_user_abort(true);
if (connection_aborted()) {
unlink('user_archives/'.$archiveName.'');
} else {
unlink('user_archives/'.$archiveName.'');
}
echo '<p>Successfully created the ZIP Archive!</p>';
}
}
?>
This seems to fix all problems.

Deleting ".part" files from folder with PHP

I'm using the following to delete all files from the specified directory.
$files = glob('path/to/temp/*');
foreach($files as $file){
if(is_file($file))
unlink($file);
}
It removes everything other than partially uploaded files eg : myfile.mp3.part
I've tried specifying .part in the file path just to see if I can force it that way :
$files = glob('path/to/temp/*.part');
But that doesn't work either.
Am I missing something here? Is there a different method for deleting non-active partial files?
$files = scandir('/path/to/temp');
foreach($files as $key => $file) {
if ( preg_match('/.*?\.part$/', $file) ) {
unlink($file);
}
}
I'm using something likes this to delete all files in a folder.
$dir = "/path/to/temp";
$files = scandir($dir);
foreach($files as $file){
$path = $dir."/".$file;
if(is_file($path)) unlink($path);
}

Code to zip uploaded files fails to delete temporary files

I guys, i'm writting code to upload file, zip them and delete tmp file.
But when i use unlink function, it do not remove all file, someone can explain to me why ?
Concerned php code :
$zip = new ZipArchive();
$target_path = 'img/products/';
$zip->open($target_path.$id_insert.'.zip', ZIPARCHIVE::CREATE);
$img_count = $_POST['count_file'];
for ($i = 1; $i <= $img_count; $i++){
$temp = 'img'.$i;
$file = $i.'-'.$id_insert.'-'.$_FILES[$temp]['name'];
$path = $target_path.basename($file);
if(move_uploaded_file($_FILES[$temp]['tmp_name'], $path)) {
$zip->addFile($path, basename($file));
$files_to_delete[] = $path;
}
}
$zip->close();
foreach($files_to_delete AS $file){
//unlink(dirname(__FILE__).'/'.$path);
}
foreach($files_to_delete AS $file){
//unlink(dirname(__FILE__).'/'.$path);
}
In this block you should replace $path with $file since that's what you're foreaching them as. You get the error because after you unlink $path the first time, the file at $path is unlinked, but every other iteration of it tries to delete the same file (which is the last one assigned to the $path variable).

Categories