Home > Backend Development > PHP Tutorial > PHP recursively deletes files in a directory but retains the example shared_PHP tutorial

PHP recursively deletes files in a directory but retains the example shared_PHP tutorial

WBOY
Release: 2016-07-13 10:30:03
Original
842 people have browsed it

Deleting directories and files using php programs has many advantages over deleting via ftp. First of all, it is troublesome to enter ftp. Then when deleting a large number of files, ftp deletion is very slow. Also, the program only wants to delete files under the folder while retaining the directory structure. This can be easily achieved with php, and there are also generated logs. , it is obviously much easier to clear the cache with a program.

1: Delete the files under the directory without deleting the directory

Copy the code The code is as follows:

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 "Deleted file: $dirName/$item
n";
                                                                                                

Two: Delete the directory and all files in the directory


Copy the code
The code is as follows:

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 "Deleted file: $dirName/$item
n";
} }
}  
}  
closedir( $handle );  
if( rmdir( $dirName ) ) echo "Directory deleted successfully: $dirName
n";





http://www.bkjia.com/PHPjc/768130.html

www.bkjia.com
truehttp: //www.bkjia.com/PHPjc/768130.html

TechArticleDeleting directories and files using the php program has many advantages over deleting via ftp. First of all, entering ftp is troublesome, and then when deleting a large number of files, ftp deletion is very slow, and the program only wants to delete files...
Related labels:
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