skwap Posted December 24, 2011 Share Posted December 24, 2011 i have made an delete files script which works for only one directory but not sub directory so i want to delete files of same extention from directory and subdirectory. My current code is <? $dir = 'hmm/'; function scanr($dir){ $arr = glob($dir.'/*.jpg'); foreach($arr as $vv){ //check if $vv is a file if(is_file($vv)){ //if file, get the filename $vx=explode('/',$vv); $file=$vx[count($vx)-1]; // if no extension delete the file unlink($vv); // print the deletion message echo $vv." deleted!<br>";}else{ // if $vv is a dir then scan it again for files scanr($vv); }} } scanr($dir); ?> Link to comment https://forums.phpfreaks.com/topic/253783-delete-files-from-directory-sub-directory/ Share on other sites More sharing options...
AGuyWithAthing Posted December 24, 2011 Share Posted December 24, 2011 This will do what you want: <?php $dir = 'del_contents'; $ext = 'jpg'; recursiveDeletion( $dir, $ext ); function recursiveDeletion( $dir, $ext ) { $directoryResource = opendir( $dir ); while( false !== ( $fs = readdir( $directoryResource ) ) ) { if( in_array( $fs, array( '.', '..' ) ) ) continue; $file = sprintf( '%s/%s', $dir, $fs ); if( is_dir( $file ) ) recursiveDeletion( $file, $ext ); else if( preg_match( sprintf( '/^.*\.%s$/', $ext ), $file ) ) printf( "File %s has %sbeen deleted.\n", $file, ( @unlink( $file ) ) ? '' : 'not ' ); } closedir($directoryResource); } It will delete everything in a directory and all its sub directories. Link to comment https://forums.phpfreaks.com/topic/253783-delete-files-from-directory-sub-directory/#findComment-1301058 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.