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).
Related
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);
}
I'm creating an upload form that when uploading files will check to see if a file with the same name already exists in the directory. If a file with the same name is found, the script should increment the file by appending the file name with a number such as test1.txt test2.txt and so on until a match is not found. This is what I have come up with so far but wanted to see if there is a different approach I should take.
Also note, my filenames are already cleaned before they enter this part of the script so my filename and extension functions are simplified.
function filename($file){
return substr($file,0,strrpos($file,'.'));
}
function extension($file){
return strtolower(substr(strrchr($file,'.'),1));
}
$new_file = 'test.txt';
$dir = 'files';
$files = scandir($dir);
$exclude = array('.','..');
foreach($files as $file){
if(!in_array($file,$exclude)){
$file_array[] = $file;
}
}
$i = 1;
while(in_array($new_file,$file_array)){
$filename = filename($new_file);
$extension = extension($new_file);
if($i>1){
$num = strlen($filename);
$filename = substr($filename,0,-1);
$new_file = $filename.$i.'.'.$extension;
} else {
$new_file = $filename.$i.'.'.$extension;
}
echo $new_file.'<br>';
echo $i.'<br>';
$i++;
}
echo $new_file;
i have been trying to rename all the files (images) in a folder on my website but it does not work. the files are not renamed.
i have an input field for 'name' i want to use that name, add a uniqid and rename all the files.
here's the code that i am using:
<?php
if(isset($_POST['submit2'])){
$name = $_POST['name'];
$directory = glob("../basic_images/*.*");
{
if ($file != "." && $file != "..") {
$newName = uniqid().$name;
rename($directory.$file, $directory.$newName);
}}}
?>
besides, do i really need to _Post the $name variable?
P.S. i want to rename all the files and then copy them to another folder.
You don't need to POST name
glob is return you every files in folder with path // example /basic_images/test.jpg
then you just do foreach to loop over files, and update its name.
$path = "../basic_images/";
$directory = glob($path,"*.*");
foreach($directory as $file){
$ext = pathinfo($file, PATHINFO_EXTENSION);
$newName = uniqid().$ext;
rename($file, $path.$newName);
}
read more about glob : http://php.net/manual/en/function.glob.php
so, i finally solved the problem. now, instead of renaming the original files and then copying them to another folder, i just create new copies of the files with new names.
This is the code final code that works for me:
if(isset($_POST['submit'])){
$path = "../posts_images/";
$files = glob("../basic_images/*.*");
foreach($files as $file){
$ext = pathinfo($file, PATHINFO_EXTENSION);
$name = $_POST['new_name'];
$pic = uniqid().$name;
$newName = $pic.'.'.$ext;
copy($file, $path.$newName);
}}
it is important to use $pic.'.'.$ext because without it the new files don't have any extension.
I am trying for the life of me to find the best way to delete all files in a single directory excluding a single file extension, ie anything that is not .zip
The current method I have used so far which successfully deletes all files is:
$files = glob('./output/*');
foreach($files as $file)
{
if(is_file($file))
unlink($file); // delete file
}
I have tried modifying this like so:
$files = glob('./output/**.{!zip}', GLOB_BRACE);
foreach($files as $file)
{
if(is_file($file))
unlink($file); // delete file
}
However, I am not hitting the desired result. I have changed the line as follows which has deleted only the zip file itself (so I can do the opposite of desired).
$files = glob('./output/*.{zip}', GLOB_BRACE);
I understand that there are other methods to read directory contents and use strpos/preg_match etc to delete accordingly. I have also seen many other methods, but these seem to be quite long winded or intended for recursive directory loops.
I am certainly not married to glob(), I would simply like to know the simplest/most efficient way to delete all files in a single directory that are not a .zip file.
Any help/advice is appreciated.
$exclude = array("zip");
$files = glob("output/*");
foreach($files as $file) {
$extension = pathinfo($file, PATHINFO_EXTENSION);
if(!in_array($extension, $exclude)) unlink($file);
}
This code works by having an array of excluded extensions, it loads up all files in a directory then checks for the extension of each file. If the extension is in the exclusion list then it doesn't get deleted. Else, it does.
This should work for you:
(I just use array_diff() to get all files which are different to *.zip and then i go through these files and unlink them)
<?php
$files = array_diff(glob("*.*"), glob("*.zip"));
foreach($files as $file) {
if(is_file($file))
unlink($file); // delete file
}
?>
How about calling to the shell? So in Linux:
$path = '/path/to/dir/';
$shell_command = escapeshellcmd('find ' . $path .' ! -name "*.zip" -exec rm -r {}');
$output = shell_exec($shell_command);
I would simply like to know the simplest/most efficient way to delete all files in a single directory that are not a .zip file.
SPL Iterators are very effective and efficient.
This is what I would use:
$folder = __DIR__;
$it = new FilesystemIterator($folder, FilesystemIterator::SKIP_DOTS);
foreach ($it as $file) {
if ($file->getExtension() !== 'zip') {
unlink($file->getFilename());
}
}
Have you tried this:
$path = "dir/";
$dir = dir($path);
while ($file = $dir->read()) {
if ($file != "." && $file != ".." && substr($file, -4) !== '.zip') {
unlink($file);
}
}
I got this working but when i look into the zip folder all the files size is 0. I tryed not adding the files to the zip and that worked, but when i try to add them to a zip the size goes to 0. Why is this.
here is my php
if(isset($_FILES['file'])){
$file_folder = "uploads/";
$zip = new ZipArchive();
$zip_name = time().".zip";
$open = $zip->open("zip/".$zip_name, ZipArchive::CREATE);
if($open === true){
for($i = 0; $i < count($_FILES['file']['name']); $i++)
{
$filename = $_FILES['file']['name'][$i];
$tmpname = $_FILES['file']['tmp_name'][$i];
move_uploaded_file($tmpname, "uploads/".$filename);
$zip->addFile($file_folder, $filename);
}
$zip->close();
if(file_exists("zip/".$zip_name)){
// zip is in there, delete the temp files
echo "Works";
for($i = 0; $i < count($_FILES['file']['name']); $i++)
{
$filenameu = $_FILES['file']['name'][$i];
unlink("uploads/".$filenameu);
}
} else {
// zip not created, give error
echo "something went wrong, try again";
}
}
}
Your problem lies with this line: $zip->addFile($file_folder, $filename);
Currently that passes a path to the /uploads/ directory as the first argument.
According to Zip::addFile documentation you should be passing the path to the file to add (this includes the file and extension).
So change your code to include the file name (you already have it as a variable $filename which is handy).
$zip->addFile($file_folder.$filename, $filename);