delete multiple files from the folder - php

how can i delete multiple files from the folder?
code:$query=$this->main_model->get($id);
if($query->num_rows()>0)
{
foreach ($query->result() as $row)
{
unlink("uploads/".$id."/".$row->img_name);
unlink("uploads/".$id."/".$row->img_name_tn);
unlink("uploads/".$id."/".$row->file);
unlink("uploads/".$id."/".$row->file2);
unlink("uploads/".$id."/Thumbs.db");
}
rmdir("uploads/".$id);
}
here is the code i used but it delete the files at ones. and how can i delete all files from the folder?

originally from php.net:
<?php
$dir = '/uploads/';
if ($handle = opendir($dir)) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") { // strip the current and previous directory items
unlink($dir . $file); // you can add some filters here, aswell, to filter datatypes, file, prefixes, suffixes, etc
}
}
closedir($handle);
}
?>

I found this at php.net:
"The shortest recursive delete possible"
function rrmdir($path) {
return is_file($path)?
#unlink($path):
array_map('rrmdir',glob($path.'/*'))==#rmdir($path)
;
}

You could do it like this:
function delete_files($dirname) {
if (is_dir($dirname))
$dir_handle = opendir($dirname);
if (!$dir_handle)
return false;
while($file = readdir($dir_handle)) {
if ($file != "." && $file != "..") {
if (!is_dir($dirname."/".$file))
unlink($dirname."/".$file);
}
}
closedir($dir_handle);
return true;
}

You need to use a recursive function. A comment from the rmdir page have written a function on how to do it, see http://www.php.net/manual/en/function.rmdir.php#98622. This code will delete the folder and everything in it.
<?php
function rrmdir($dir) {
if (is_dir($dir)) {
$objects = scandir($dir);
foreach ($objects as $object) {
if ($object != "." && $object != "..") {
if (filetype($dir."/".$object) == "dir") rrmdir($dir."/".$object); else unlink($dir."/".$object);
}
}
reset($objects);
rmdir($dir);
}
}
?>

Related

PHP Multi Directory delete

So I'm creating an image upload site and I need to delete multiple directories and files simultaneously. I have managed to create code that does the job however I'm unsure whether this is 'good code' as I'm repeating myself.
Is there a better way to write the below?
$dirname = 'uploads/'.$album_id;
$dirnamethumb = 'uploads/thumbs/'.$album_id;
if (is_dir($dirname))
$dir_handle = opendir($dirname);
if (!$dir_handle)
return false;
while($file = readdir($dir_handle)) {
if ($file != "." && $file != "..") {
if (!is_dir($dirname."/".$file))
unlink($dirname."/".$file);
else
delete_directory($dirname.'/'.$file);
}
}
if (is_dir($dirnamethumb))
$dir_handle = opendir($dirnamethumb);
if (!$dir_handle)
return false;
while($file = readdir($dir_handle)) {
if ($file != "." && $file != "..") {
if (!is_dir($dirnamethumb."/".$file))
unlink($dirnamethumb."/".$file);
else
delete_directory($dirnamethumb.'/'.$file);
}
}
closedir($dir_handle);
rmdir($dirname);
rmdir($dirnamethumb);
return true;
Thank you in advance for your help!
Why not try this recursive function from similar question
function rrmdir($dir) {
foreach(glob($dir . '/*') as $file) {
if(is_dir($file))
rrmdir($file);
else
unlink($file);
} rmdir($dir);
}
try this,
$dir = '/path/to/some/dir/'; // notice: trailing slash!
if ($handle = opendir($dir)) {
while (false !== ($entry = readdir($handle))) {
if (is_dir($dir . $entry) ) {
rmdir($dir . $entry);
}
}
closedir($handle);
}
?>

php deleting a specific folder and all its contents

I'm using php to delete folders containing images of posts that where deleted. I'm using the code below which I found online and does a good job.
I want to know how can I delete only a specific folder in a folder when there are other folders in it.
When I using the code below, how is it possible to do this?
Using: /dev/images/norman/8 -> Will not delete folder 8
Using: /dev/images/norman/ -> Will delete all folders
Eg:
/dev/images/norman/8 -> I need to delete only this folder
/dev/images/norman/9
/dev/images/norman/10
/dev/images/norman/11
/dev/images/norman/12
<?php
$path = $_SERVER['DOCUMENT_ROOT'].'/dev/images/norman/8';
emptyDir($path);
function emptyDir($path) {
// INITIALIZE THE DEBUG STRING
$debugStr = '';
$debugStr .= "Deleting Contents Of: $path<br /><br />";
// PARSE THE FOLDER
if ($handle = opendir($path)) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
// IF IT"S A FILE THEN DELETE IT
if(is_file($path."/".$file)) {
if(unlink($path."/".$file)) {
$debugStr .= "Deleted File: ".$file."<br />";
}
} else {
// IT IS A DIRECTORY
// CRAWL THROUGH THE DIRECTORY AND DELETE IT'S CONTENTS
if($handle2 = opendir($path."/".$file)) {
while (false !== ($file2 = readdir($handle2))) {
if ($file2 != "." && $file2 != "..") {
if(unlink($path."/".$file."/".$file2)) {
$debugStr .= "Deleted File: $file/$file2<br />";
}
}
}
}
if(rmdir($path."/".$file)) {
$debugStr .= "Directory: ".$file."<br />";
}
}
}
}
}
echo $debugStr;
}
?>
<?php
delete_directory($dirname) {
if (is_dir($dirname))
$dir_handle = opendir($dirname);
if (!$dir_handle)
return false;
while($file = readdir($dir_handle)) {
if ($file != "." && $file != "..") {
if (!is_dir($dirname."/".$file))
unlink($dirname."/".$file);
else
delete_directory($dirname.'/'.$file);
}
}
closedir($dir_handle);
rmdir($dirname);
return true;
}
?>
if you are using, version 5.1 and above,
<?php
function deleteDir($dir) {
$iterator = new RecursiveDirectoryIterator($dir);
foreach (new RecursiveIteratorIterator($iterator, RecursiveIteratorIterator::CHILD_FIRST) as $file)
{
if ($file->isDir()) {
rmdir($file->getPathname());
} else {
unlink($file->getPathname());
}
}
rmdir($dir);
}
deleteDir("temporary");
?>
You want to hear about rmdir.
if(is_file($path."/".$file)) {
if(unlink($path."/".$file)) {
$debugStr .= "Deleted File: ".$file."<br />";
}
} else {
if(rmdir($path."/".$file)) {
$debugStr .= "Deleted Directory: ".$file."<br />";
}
}
EDIT: as rmdir can only handle empty dirs, you may use this solution as reported in rmdir's page comments:
function rrmdir($dir) {
foreach(glob($dir . '/*') as $file) {
if(is_dir($file))
rrmdir($file);
else
unlink($file);
}
rmdir($dir);
}
It just recursively deletes everything in $dir, then gets rid of directory itself.
I added an $exclude param to your function, this param it's an array with the names of directories you want to exclude from being deleted, like so:
$path = $_SERVER['DOCUMENT_ROOT'].'/dev/images/norman/';
emptyDir($path); //will delete all under /norman/
emptyDir($path, array('8')); //will delete all under /norman/ except dir 8
emptyDir($path, array('8','10')); //will delete all under /norman/ except dir 8 and 10
function emptyDir($path,$exclude=false) {
// INITIALIZE THE DEBUG STRING
$debugStr = '';
$debugStr .= "Deleting Contents Of: $path<br /><br />";
if (!$exclude) {
$exclude = array();
}
// PARSE THE FOLDER
if ($handle = opendir($path)) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
// IF IT"S A FILE THEN DELETE IT
if(is_file($path."/".$file)) {
if(unlink($path."/".$file)) {
$debugStr .= "Deleted File: ".$file."<br />";
}
} else if (!in_array($file, $exclude)) {
// IT IS A DIRECTORY
// CRAWL THROUGH THE DIRECTORY AND DELETE IT'S CONTENTS
if($handle2 = opendir($path."/".$file)) {
while (false !== ($file2 = readdir($handle2))) {
if ($file2 != "." && $file2 != "..") {
if(unlink($path."/".$file."/".$file2)) {
$debugStr .= "Deleted File: $file/$file2<br />";
}
}
}
}
if(rmdir($path."/".$file)) {
$debugStr .= "Directory: ".$file."<br />";
}
}
}
}
}
echo $debugStr;
}
You can use system commands ex. exec("rm -rf {$dirPath}"); or if you want to do it by PHP you have to go recursive, loops won't do it right.
public function deleteDir($path) {
if ($handle = opendir($path)) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
// IF IT"S A FILE THEN DELETE IT
if(is_file($path."/".$file)) {
if(unlink($path."/".$file)) {
$debugStr .= "Deleted File: ".$file."<br />";
}
} else {
deleteDir($path."/".$file."/");
rmdir($path."/".$file);
}
}
}
}
}
When I using the code below, how is it possible to do this? Using:
/dev/images/norman/8 -> Will not delete folder 8 Using:
/dev/images/norman/ -> Will delete all folders
I think your problem is that you're missing "/" at the end of "/dev/images/norman/8"
$path='./ggg';
rrmdir($path);
function rrmdir($dir) {
if (is_dir($dir)) {
$objects = scandir($dir);
foreach ($objects as $object) {
if ($object != "." && $object != "..") {
if (filetype($dir."/".$object) == "dir") rrmdir($dir."/".$object); else unlink($dir."/".$object);
}
}
reset($objects);
rmdir($dir);
}
}

Opendir get array of files before files in sub folder

I have a function which returns an array of files in a folder recursive.
protected function getFiles($base) {
$files = array();
if(!is_dir($base)) return $files;
if (($handle = opendir($base)) != false) {
while (false !== ($file = readdir($handle))) {
if ($file == "." || $file == "..") continue;
if(is_dir("$base/$file")) {
$subfiles = $this->getFiles("$base/$file");
$files = array_merge($files, $subfiles);
} else {
if(File::type($file,false) == "xml")
$files[] = "$base/$file";
}
}
closedir($handle);
}
return $files;
}
How can I modify this so that it always lists the root files first before any sub folders? At the moment by default the folders always come first.
You may want to take a look at the PHP SPL DirectoryIterator Class. You can instantiate the object and then quickly iterate over to segment out directories vs. files vs. links and get the full SplFileInfo object for each (which makes it really easy to get whatever info you want about the files).
$directory = '/path/to/directory';
$iterator = new DirectoryIterator($directory);
$dirs = array();
$files = array();
$links = array();
foreach($iterator as $obj) {
if($obj->isFile()) {
$files[] = $obj;
} else if ($obj->isDir()) {
$dirs[] = $obj;
} else if ($obj->isLink()) {
$links[] = $obj;
}
}
Sorry just realized you wanted to do it recursively. Well for that use RecursiveDirectoryIterator , but concept is much the same.
Just create an array of sub-directories while you loop the directory pointer, and iterate the array of directories at the end:
protected function getFiles($base) {
$files = $dirs = array();
if(!is_dir($base)) return $files;
if (($handle = opendir($base)) != false) {
while (false !== ($file = readdir($handle))) {
if ($file == "." || $file == "..") continue;
if(is_dir("$base/$file")) {
$dirs[] = "$base/$file";
} else {
if(File::type($file,false) == "xml")
$files[] = "$base/$file";
}
}
closedir($handle);
foreach ($dirs as $dir) {
$subfiles = $this->getFiles($dir);
$files = array_merge($files, $subfiles);
}
}
return $files;
}
Use two arrays one for the files in the current folder and one for the those in subfolders then merge them.
protected function getFiles($base) {
$files = array();
$subFiles = array();
if(!is_dir($base)) return $files;
if (($handle = opendir($base)) != false) {
while (false !== ($file = readdir($handle))) {
if ($file == "." || $file == "..") continue;
if(is_dir("$base/$file")) {
$subFiles = array_merge($subFiles, $this->getFiles("$base/$file"));
} else {
if(File::type($file,false) == "xml")
$files[] = "$base/$file";
}
}
closedir($handle);
}
return array_merge($files, $subFiles);
}

Remove all files, folders and their subfolders with php [duplicate]

This question already has answers here:
Delete directory with files in it?
(34 answers)
Closed 5 years ago.
I need a script which can remove a whole directory with all their subfolders, files and etc. I tried with this function which I found in internet before few months ago but it not work completely.
function deleteFile($dir) {
if(substr($dir, strlen($dir)-1, 1) != '/') {
$dir .= '/';
}
if($handle = opendir($dir)) {
while($obj = readdir($handle)) {
if($obj != '.' && $obj != '..') {
if(is_dir($dir.$obj)) {
if(!deleteFile($dir.$obj)) {
echo $dir.$obj."<br />";
return false;
}
}
elseif(is_file($dir.$obj)) {
if(!unlink($dir.$obj)) {
echo $dir.$obj."<br />";
return false;
}
}
}
}
closedir($handle);
if(!#rmdir($dir)) {
echo $dir.'<br />';
return false;
}
return true;
}
return true;
}
For the test I use a unpacked archive of prestashop and I try to delete the folder where archive is unpacked but it doesn't work.
/home/***/public_html/prestashop/img/p/3/
/home/***/public_html/prestashop/img/p/3
/home/***/public_html/prestashop/img/p
/home/***/public_html/prestashop/img
These are the problem folders. At the first time I think - "May is a problem with the chmod of the files" but when I test with all files chmod permission 755 (after that with 777) - the result was the same.
<?php
function rrmdir($dir) {
if (is_dir($dir)) {
$objects = scandir($dir);
foreach ($objects as $object) {
if ($object != "." && $object != "..") {
if (filetype($dir."/".$object) == "dir")
rrmdir($dir."/".$object);
else unlink ($dir."/".$object);
}
}
reset($objects);
rmdir($dir);
}
}
?>
Try out the above code from php.net
Worked fine for me
function delete_files($dir) {
foreach(glob($dir . '/*') as $file) {
if(is_dir($file)) delete_files($file); else unlink($file);
} rmdir($dir);
}
You can use a cleaner method for doing a recursive delete of a directory.
Example:
function recursiveRemove($dir) {
$structure = glob(rtrim($dir, "/").'/*');
if (is_array($structure)) {
foreach($structure as $file) {
if (is_dir($file)) recursiveRemove($file);
elseif (is_file($file)) unlink($file);
}
}
rmdir($dir);
}
Usage:
recursiveRemove("test/dir/");
The easiest and the best way using the system() method
$dir = dirname ( "/log" );
if ($handle = opendir($dir)) {
while (( $file = readdir($handle)) !== false ) {
if ($file != "." && $file != "..") {
system("rm -rf ".escapeshellarg($dir.'/'.$file));
}
}
}
closedir($handle);
/**
* Deletes a directory and all files and folders under it
* #return Null
* #param $dir String Directory Path
*/
function rmdir_files($dir) {
$dh = opendir($dir);
if ($dh) {
while($file = readdir($dh)) {
if (!in_array($file, array('.', '..'))) {
if (is_file($dir.$file)) {
unlink($dir.$file);
}
else if (is_dir($dir.$file)) {
rmdir_files($dir.$file);
}
}
}
rmdir($dir);
}
}

Delete a directory not empty

rmdir("./uploads/temp/".$user."/");
I have many files in a directory I wish to remove in my PHP script, however these is no way for me to unlink() the file first. Is there a way I co do
unlink(* FROM (dir=)) // don't downvote the long shot
// delete all files from the dir first
// then delete that dir
Reference a directory has to be empty in order to delete it, see php.net/manual/en/function.rmdir.php
You can use the DirectoryIterator and unlink together.
use this
function delete_directory($dirname) {
if (is_dir($dirname))
$dir_handle = opendir($dirname);
if (!$dir_handle)
return false;
while($file = readdir($dir_handle)) {
if ($file != "." && $file != "..") {
if (!is_dir($dirname."/".$file))
unlink($dirname."/".$file);
else
delete_directory($dirname.'/'.$file);
}
}
closedir($dir_handle);
rmdir($dirname);
return true;
}
This code can easily be improved upon, as it's a quick hack, but it takes a directory as an argument and then uses functional recursion to delete all files and folders within, and then finally removes the directory. Nice and quick, too.
There is no other way except to delete all files first using one way or another and then remove directory.
public static function deleteDir($dirPath) {
if (! is_dir($dirPath)) {
throw new InvalidArgumentException('$dirPath must be a directory');
}
if (substr($dirPath, strlen($dirPath) - 1, 1) != '/') {
$dirPath .= '/';
}
$files = glob($dirPath . '*', GLOB_MARK);
foreach ($files as $file) {
if (is_dir($file)) {
self::deleteDir($file);
} else {
unlink($file);
}
}
rmdir($dirPath);
}
Try using glob to loop over the files in the directory to delete
foreach (glob('/path/to/directory/*') as $file){
unlink('/path/to/directory/' . $file);
}
Check this http://lixlpixel.org/recursive_function/php/recursive_directory_delete/
function recursive_remove_directory($directory, $empty=FALSE)
{
if(substr($directory,-1) == '/')
{
$directory = substr($directory,0,-1);
}
if(!file_exists($directory) || !is_dir($directory))
{
return FALSE;
}elseif(is_readable($directory))
{
$handle = opendir($directory);
while (FALSE !== ($item = readdir($handle)))
{
if($item != '.' && $item != '..')
{
$path = $directory.'/'.$item;
if(is_dir($path))
{
recursive_remove_directory($path);
}else{
unlink($path);
}
}
}
closedir($handle);
if($empty == FALSE)
{
if(!rmdir($directory))
{
return FALSE;
}
}
}
return TRUE;
}
You can delete it recursively:
public function delete_folder ($path) {
$handle = opendir($path);
while ($file = readdir($handle)) {
if ($file != '..' && $file != '.') {
if (is_file($path . DS . $file))
unlink($path . DS . $file);
else
delete_folder($path . DS . $file);
}
}
closedir($handle);
rmdir($tmp_path);
}
delete_folder('path/to/folder');

Categories