PHP example sharing: Detailed explanation of deleting all files in a directory through recursion_PHP tutorial

WBOY
Release: 2016-07-13 10:29:46
Original
838 people have browsed it

Post the code first:

Copy code The code is as follows:

function delFile($dirName){
if ($handle = opendir("$dirName")){
while (($item = readdir($handle))!=false){
if ($item!="." && $item!= "..") {
if ( is_dir( "$dirName/$item" ) ) {
delFile( "$dirName/$item" );
} else unlink("$dirName/$item ");
}
}
closedir($handle);
}
?>


delFile('/home/sources');
?>

Let’s first explain a few functions:

opendir(): Function opens a directory handle and can be used by closedir(), readdir() and rewinddir().

If successful, this function returns a directory stream, otherwise it returns false and an error. You can hide error output by prepending "@" to the function name. For example $dir=@ opendir("image");

readdir(): Returns the entries in the directory handle opened by the opendir function, that is, the file names in the folder are returned in order, in accordance with the sorting method specified in the file system.

id_dir(): Check whether the parameter file is a directory, and return true if so.

un_link(): Delete the specified file.

So the program execution idea is: the function calls the main directory, and then sequentially checks whether each file is a directory. If it is a directory, the function is called recursively, and the files that are not directories are deleted until all files are traversed.

This program only deletes the contents of the folder, but not the folder itself. If you want to achieve this purpose, just add the following code:

Copy code The code is as follows:

rmdir($dirName);

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/770580.htmlTechArticlePaste the code first: Copy the code as follows: ?php function delFile($dirName){ if ($handle = opendir ("$dirName")){ while (($item = readdir($handle))!=false){ if ($item!="." $item!="....
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!