Home > Backend Development > PHP Tutorial > Detailed explanation of how to delete a directory and all files in the directory with PHP_PHP Tutorial

Detailed explanation of how to delete a directory and all files in the directory with PHP_PHP Tutorial

WBOY
Release: 2016-07-21 15:08:32
Original
1273 people have browsed it

Function Code 1: Delete the directory and all files in the directory

Copy the code The code is as follows:

//Loop to delete directories and files function
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 deleted successfully: $dirName/ $item
n";
}
}
}
closedir( $handle );
if( rmdir( $dirName ) )echo " Directory deleted successfully: $dirName
n”;
}
}
?>

Function code 2: Only delete files in the specified directory, not the directory folder .
Copy code The code is as follows:

//Loop all 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 deleted successfully: $dirName/$item
n";
}
}
}
closedir( $handle );
}
}
?>

Usage example:
Assume that it needs to be deleted A sibling directory named "upload" is all the files in this directory. You can complete it with the following code:
Copy the code The code is as follows:

delDirAndFile( 'upload');
?>
Suppose you need to delete all files in a directory named "upload" (but do not need to delete the directory folder), you can do the following Code completion:
delFileUnderDir( 'upload');
?>

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/327460.htmlTechArticleFunction code 1: Delete the directory and all files in the directory Copy code The code is as follows: //Delete directories and files in a loop function function delDirAndFile( $dirName ) { if ( $handle = opendir...
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template