Delete multiple files from a folder

How can I delete multiple files from a 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 deletes the files in them. and how can I delete all files from a folder?

+4
source share
4 answers

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); } ?> 
+3
source

I found this on php.net :

 "The shortest recursive delete possible" function rrmdir($path) { return is_file($path)? @unlink($path): array_map('rrmdir',glob($path.'/*')) ==@rmdir ($path) ; } 
+2
source

You need to use a recursive function. The comment on the rmdir page wrote a function on how to do this, 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); } } ?> 
+1
source

You can do it as follows:

 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; } 
+1
source

All Articles