Home>Article>Backend Development> How to delete the current directory and all files under it in PHP? (code example)

How to delete the current directory and all files under it in PHP? (code example)

青灯夜游
青灯夜游 forward
2019-02-26 11:25:01 1928browse

This article brings you an introduction to how PHP deletes the current directory and all files in it? (Code sample) has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Use PHP to traverse all directories and files under a directory, and delete the directory and all subdirectories and files under the directory. This code is implemented recursively.

【Video tutorial recommendation:PHP tutorial

Functions used:

scandir($path) Traverses all files in a directory and returns an array.
unlink($filename) Delete the file.
rmdir($path) only deletes empty folders.

PHP code:

/** * 删除当前目录及其目录下的所有目录和文件 * @param string $path 待删除的目录 * @note $path路径结尾不要有斜杠/(例如:正确[$path='./static/image'],错误[$path='./static/image/']) */ function deleteDir($path) { if (is_dir($path)) { //扫描一个目录内的所有目录和文件并返回数组 $dirs = scandir($path); foreach ($dirs as $dir) { //排除目录中的当前目录(.)和上一级目录(..) if ($dir != '.' && $dir != '..') { //如果是目录则递归子目录,继续操作 $sonDir = $path.'/'.$dir; if (is_dir($sonDir)) { //递归删除 deleteDir($sonDir); //目录内的子目录和文件删除后删除空目录 @rmdir($sonDir); } else { //如果是文件直接删除 @unlink($sonDir); } } } @rmdir($path); } }

The above is the entire content of this article, I hope it will be helpful to everyone's learning. For more exciting content, you can pay attention to the relevant tutorial columns of the PHP Chinese website! ! !

The above is the detailed content of How to delete the current directory and all files under it in PHP? (code example). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:cnblogs.com. If there is any infringement, please contact admin@php.cn delete