note 96514 deleted from function.readdir by danbrown
| From: | danbrown@php.net | Date: | Wed, 03 Mar 2010 14:34:44 +0000 |
| Subject: | note 96514 deleted from function.readdir by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-166567@lists.php.net to get a copy of this message | ||
Note Submitter: cesar at sagie dot es
----
Derived from ianatvirante.com's example.
this script removes a file from a folder AND its subfolders. Just in case somebody finds it useful.
Here is the code:
<?php
//define the path as relative
$path = "path to parent folder";
$my_file = "name of file to be deleted";
//using the opendir function
$dir_handle = @opendir($path) or die("Unable to open $path");
echo "Delete all $my_file files from folder $path & subfolders<br/>";
list_dir($dir_handle,$path,$my_file);
function list_dir($dir_handle,$path,$my_file)
{
// print_r ($dir_handle);
echo "<ol>";
//running the while loop
while (false !== ($file = readdir($dir_handle))) {
$dir =$path.'/'.$file;
if(is_dir($dir) && $file != '.' && $file !='..' )
{
$handle = @opendir($dir) or die("undable to open file $file");
echo '<li><a href=' . $path . '/' . $file .
'>' .$file . '</a></li>';
list_dir($handle, $dir, $my_file);
}elseif($file != '.' && $file !='..')
{
echo '<li><a href=' . $path . '/' . $file . '>' .$file
. '</a></li>';
if ($file == $my_file){
unlink($path.'/'.$file);
echo $path.'/'.$file. ' deleted.<br/>';
}
}
}
echo "</ol>";
//closing the directory
closedir($dir_handle);
}
?>