PHP delete directory and all files under the directory detailed explanation

  • 2020-06-07 04:05:55
  • OfStack

Function code 1: Delete the directory and all files under the directory

// Loop delete directory and file functions 
function delDirAndFile( $dirName )
{
if ( $handle = opendir( "$dirName" ) ) {
while ( false !== ( $item = readdir( $handle ) ) ) {
if ( $item != "." && $item != ".." ) {
if ( is_dir( "$dirName/$item" ) ) {
delDirAndFile( "$dirName/$item" );
} else {
if( unlink( "$dirName/$item" ) )echo " File was deleted successfully:  $dirName/$item
\n " ;
}
}
}
closedir( $handle );
if( rmdir( $dirName ) )echo  "Successfully deleted directory:  $dirName
\n " ;
}
}
?>

Function code 2: delete only the files in the specified directory, not the directory folder.

// Loop through all the files in the directory 
function delFileUnderDir( $dirName )
{
if ( $handle = opendir( "$dirName" ) ) {
while ( false !== ( $item = readdir( $handle ) ) ) {
if ( $item != "." && $item != ".." ) {
if ( is_dir( "$dirName/$item" ) ) {
delFileUnderDir( "$dirName/$item" );
} else {
if( unlink( "$dirName/$item" ) )echo " File was deleted successfully:  $dirName/$item
\n " ;
}
}
}
closedir( $handle );
}
}
?>

Examples of usage:
Suppose you want to delete a sibling directory named "upload", that is, all the files in this directory. You can do this by:

delDirAndFile( 'upload');
?>
 Suppose you want to delete 1 Named" upload "All files in the" directory (but no need to delete the directory folder), you can do this by: 
delFileUnderDir( 'upload');
?>

Related articles: