Deleting files matching a specific file extension recursivly? - php

I would like to delete all files matching a particular extension in a specified directory and all subtree. I suppose I should be using using unlink but some help would be highly appreciated... Thank you!

you need a combination of this
Recursive File Search (PHP)
And the unlink / delete
You should be able to edit the example instead of echoing the file, to delete it

To delete specific extension files from sub directories, you can use the following function. Example:
<?php
function delete_recursively_($path,$match){
static $deleted = 0,
$dsize = 0;
$dirs = glob($path."*");
$files = glob($path.$match);
foreach($files as $file){
if(is_file($file)){
$deleted_size += filesize($file);
unlink($file);
$deleted++;
}
}
foreach($dirs as $dir){
if(is_dir($dir)){
$dir = basename($dir) . "/";
delete_recursively_($path.$dir,$match);
}
}
return "$deleted files deleted with a total size of $deleted_size bytes";
}
?>
e.g. To remove all text files you can use it as follows:
<?php echo delete_recursively_('/home/username/directory/', '.txt'); ?>

Related

Unable to Rename the latest file in a folder with PHP

I want to rename the latest added file from a folder, but somehow my code isn't working. Could please help!
For example, if the latest file is "file_0202.json"
And I want to Change it to "file.json"
Here is my Code
<?php
$files = scandir('content/myfiles', SCANDIR_SORT_DESCENDING);
$selected_file = $files[0];
$new_filename = preg_replace('/_[^_.]*\./', '.', $selected_file);
if(rename($selected_file, $new_filename, ))
{
echo 'renamed';
}
else {
echo 'can not rename';
}
?>
It's better if you use glob(). glob() returns the path and filename used.
Then you have to sort by the file that was last changed. You can use usort and filemtime for that.
$files = glob('content/myfiles/*.*');
usort($files,function($a,$b){return filemtime($b) <=> filemtime($a);});
$selected_file = $files[0];
$new_filename = preg_replace('/_[^_.]*\./', '.', $selected_file);
if(rename($selected_file, $new_filename))
{
echo 'renamed';
}
else {
echo 'can not rename';
}
Instead of *.* you can restrict the searched files if necessary. As an example *.json . Be careful with your regular expression so that it doesn't change a path.

how to check for certain file extension in a folder with php [duplicate]

This question already has answers here:
Getting the names of all files in a directory with PHP
(15 answers)
Closed 4 years ago.
I have a folder named uploads with a lot of files in it. I want to find out if there is a .zip file inside it. How can i check if there is a .zip file inside it with php?
Use the glob() function.
$result = glob("my/folder/uploads/*.zip");
It will return an array with the *.zip-files.
Answer is already given by #Bemhard, i am adding more information for future use:
If you want to run script inside your uploads folder than you just need to call glob('*.zip').
<?php
foreach(glob('*.zip') as $file){
echo $file."<br/>";
}
?>
If you have multiple folders and containing multiple zip files inside the folders, than you just need to run script from root.
<?php
$dir = __DIR__; // will get the exact path
$dirs = array_filter(glob('*'), 'is_dir'); // filter is directory or not.
$i = 1;
foreach ($dirs as $key => $value) {
foreach(glob($value.'/*.zip') as $file){
echo $file."<br/>"; // this will print all files inside the folders.
}
$i++;
}
?>
One Extra point, if you want to remove all zip files with this activity, than you just need to unlink file by:
<?php
$dir = __DIR__; // will get the exact path
$dirs = array_filter(glob('*'), 'is_dir'); // filter is directory or not.
$i = 1;
foreach ($dirs as $key => $value) {
foreach(glob($value.'/*.zip') as $file){
echo $file."<br/>"; // this will print all files inside the folders.
unlink($file); // this will remove all files.
}
$i++;
}
?>
References:
Unlink
Glob
This also could help, using scandir and pathinfo
/**
*
* #param string $directoryPath the directory to scan
* #param string $extension the extintion e.g zip
* #return []
*/
function getFilesByExtension($directoryPath, $extension)
{
$filesRet = [];
$files = scandir($directoryPath);
if(!$files) return $filesRet;
foreach ($files as $file) {
if(pathinfo($file)['extension'] === $extension)
$filesRet[]= $file;
}
return $filesRet;
}
it can be used like
var_dump(getFilesByExtension("uploads/","zip"));

On creating zip file by php I get two files instead of one

I'm struggling around with a simple PHP functionality: Creating a ZIP Archive with some files in.
The problem is, it does not create only one file called filename.zip but two files called filename.zip.a07600 and filename.zip.b07600. Pls. see the following screenshot:
The two files are perfect in size and I even can rename each of them to filename.zip and extract it without any problems.
Can anybody tell me what is going wrong???
function zipFilesAndDownload_Defect($archive_file_name, $archiveDir, $file_path = array(), $files_array = array()) {
// Archive File Name
$archive_file = $archiveDir."/".$archive_file_name;
// Time-to-live
$archiveTTL = 86400; // 1 day
// Delete old zip file
#unlink($archive_file);
// Create the object
$zip = new ZipArchive();
// Create the file and throw the error if unsuccessful
if ($zip->open($archive_file, ZIPARCHIVE::CREATE) !== TRUE) {
$response->res = "Cannot open '$archive_file'";
return $response;
}
// Add each file of $file_name array to archive
$i = 0;
foreach($files_array as $value){
$expl = explode("/", $value);
$file = $expl[(count($expl)-1)];
$path_file = $file_path[$i] . "/" . $file;
$size = round((filesize ($path_file) / 1024), 0);
if(file_exists($path_file)){
$zip->addFile($path_file, $file);
}
$i++;
}
$zip->close();
// Then send the headers to redirect to the ZIP file
header("HTTP/1.1 303 See Other"); // 303 is technically correct for this type of redirect
header("Location: $archive_file");
exit;
}
The code which calls the function is a file with a switch-case... it is called itself by an ajax-call:
case "zdl":
$files_array = array();
$file_path = array();
foreach ($dbh->query("select GUID, DIRECTORY, BASENAME, ELEMENTID from SMDMS where ELEMENTID = ".$osguid." and PROJECTID = ".$osproject.";") as $subrow) {
$archive_file_name = $subrow['ELEMENTID'].".zip";
$archiveDir = "../".$subrow['DIRECTORY'];
$files_array[] = $archiveDir.DIR_SEPARATOR.$subrow['BASENAME'];
$file_path[] = $archiveDir;
}
zipFilesAndDownload_Defect($archive_file_name, $archiveDir, $file_path, $files_array);
break;
One more code... I tried to rename the latest 123456.zip.a01234 file to 123456.zip and then unlink the old 123456.zip.a01234 (and all prior added .a01234 files) with this function:
function zip_file_exists($pathfile){
$arr = array();
$dir = dirname($pathfile);
$renamed = 0;
foreach(glob($pathfile.'.*') as $file) {
$path_parts = pathinfo($file);
$dirname = $path_parts['dirname'];
$basename = $path_parts['basename'];
$extension = $path_parts['extension'];
$filename = $path_parts['filename'];
if($renamed == 0){
$old_name = $file;
$new_name = str_replace(".".$extension, "", $file);
#copy($old_name, $new_name);
#unlink($old_name);
$renamed = 1;
//file_put_contents($dir."/test.txt", "old_name: ".$old_name." - new_name: ".$new_name." - dirname: ".$dirname." - basename: ".$basename." - extension: ".$extension." - filename: ".$filename." - test: ".$test);
}else{
#unlink($file);
}
}
}
In short: copy works, rename didn't work and "unlink"-doesn't work at all... I'm out of ideas now... :(
ONE MORE TRY: I placed the output of $zip->getStatusString() in a variable and wrote it to a log file... the log entry it produced is: Renaming temporary file failed: No such file or directory.
But as you can see in the graphic above the file 43051221.zip.a07200 is located in the directory where the zip-lib opens it temporarily.
Thank you in advance for your help!
So, after struggling around for days... It was so simple:
Actually I work ONLY on *nix Servers so in my scripts I created the folders dynamically with 0777 Perms. I didn't know that IIS doesn't accept this permissions format at all!
So I remoted to the server, right clicked on the folder Documents (the hierarchically most upper folder of all dynamically added files and folders) and gave full control to all users I found.
Now it works perfect!!! The only thing that would be interesting now is: is this dangerous of any reason???
Thanks for your good will answers...
My suspicion is that your script is hitting the PHP script timeout. PHP zip creates a temporary file to zip in to where the filename is yourfilename.zip.some_random_number. This file is renamed to yourfilename.zip when the zip file is closed. If the script times out it will probably just get left there.
Try reducing the number of files to zip, or increasing the script timeout with set_time_limit()
http://php.net/manual/en/function.set-time-limit.php

PHP - Deleting folder/files only if there are no more in there

$value can = a folder structure to the language file. Example: languages/english.php
$value can also = the files name. Example: english.php
So I need to get the current folder that $value is in and delete the folder ONLY if there are no other files/folders within that directory (after deleting the actual file as I am doing already, ofcourse).
foreach($module['languages'] as $lang => $langFile)
{
foreach ($langFile as $type => $value)
{
#unlink($module_path . '/' . $value);
// Now I need to delete the folder ONLY if there are no other directories inside the folder where it is currently at.
// And ONLY if there are NO OTHER files within that folder also.
}
}
How can I do this?? And wondering if this can be done without using a while loop, since a while loop within a foreach loop could take some time, and need this to be as quick as possible.
And just FYI, the $module_path should never be deleted. So if $value = english.php, it should never delete the $module_path. Ofcourse, there will always be another file in there, so checking for this is not necessary, but won't hurt either way.
Thanks guys :)
EDIT
Ok, now I'm using this code here and it is NOT working, it is not removing the folders or the files, and I don't get any errors either... so not sure what the problem is here:
foreach($module['languages'] as $lang => $langFile)
{
foreach ($langFile as $type => $value)
{
if (#unlink($module_path . '/' . $value))
#rmdir(dirname($module_path . '/' . $value));
}
}
NEVERMIND, this works a CHARM!!! Cheers Everyone!!
The easyest way is try to use rmdir. This don't delete folder if it is not empty
rmdir($module_path);
also you can check is folder empty by
if(count(glob($module_path.'*'))<3)//delete
2 for . and ..
UPD: as I reviewed maybe you should replace $module_path by dirname($module_path.'.'.$value);
Since the directory you care about might be part of the $value, you need to use dirname to figure out what the parent directory is, you can't just assume that it's $module_path.
$file_path = $module_path . '/' . $value;
if (#unlink($file_path)) {
#rmdir(dirname($file_path));
}
if (is_file($value)) {
unlink($value);
} else if (is_dir($value)) {
if (count(scandir($value)) == 2) }
unlink($value)
}
}
http://php.net/manual/en/function.is-dir.php
http://www.php.net/manual/en/function.scandir.php
The code below will take a path, check if it is a file (i.e. not a directory). If it is a file, it will extract the directory name, then delete the file, then iterate over the dir and count the files in it, if the files are zero it'll delete the dir.
Code is as an example and should work, however privileges and environment setup may result in it not working.
<?php
if(!is_dir ( string $filename )){ //if it is a file
$fileDir = dirname ( $filename );
if ($handle = opendir($fileDir)) {
echo "Directory handle: $handle\n";
echo "Files:\n";
$numFiles=0;
//delete the file
unlink($myFile);
//Loop the dir and count the file in it
while (false !== ($file = readdir($handle))) {
$numFiles = $numFiles + 1;
}
if($numFiles == 0) {
//delete the dir
rmdir($fileDir);
}
closedir($handle);
}
}
?>

I need to find a file in directory and copy it to a different directory

I merely have the file name, without extension (.txt, .eps, etc.)
The directory has several subfolders. So, the file could be anywhere.
How can I seek the filename, without the extension, and copy it to different directory?
http://www.pgregg.com/projects/php/preg_find/preg_find.php.txt seems to be exactly what you need, to find the file. then just use the normal php copy() command http://php.net/manual/en/function.copy.php to copy it.
https://stackoverflow.com/search?q=php+recursive+file
have a look at this http://php.net/manual/en/function.copy.php
as for seeking filenames, could use a database to log where the files are? and use that log to find your files
I found that scandir() is the fastest method for such operations:
function findRecursive($folder, $file) {
foreach (scandir($folder) as $filename) {
$path = $folder . '/' . $filename;
# $filename starts with desired string
if (strpos($filename, $file) === 0) {
return $path;
}
# search sub-directories
if (is_dir($path)) {
$result = findRecursive($path);
if ($result !== NULL) {
return $result;
}
}
}
}
For copying the file, you can use copy():
copy(findRecursive($folder, $partOfFilename), $targetFile);

Categories