Home > Backend Development > PHP Problem > How to delete the current folder in php

How to delete the current folder in php

藏色散人
Release: 2023-03-12 09:42:02
Original
2422 people have browsed it

php method to delete the current folder: 1. Scan all directories and files in a directory and return an array; 2. Exclude the current directory and the upper-level directory in the directory; 3. Subdirectories within the directory Delete the empty directory after deleting the files; 4. Delete it through rmdir.

How to delete the current folder in php

The operating environment of this article: Windows7 system, PHP7.1 version, Dell G3 computer

How to delete the current folder with php?

PHP deletes the current directory and all files in it

Use PHP to traverse all directories and files in a directory and delete the directory and its For all subdirectories and files in the directory, this code is implemented recursively.

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='./linuxidc/image'],错误[$path='./linuxidc/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);
    }
}
Copy after login

Recommended learning: "PHP Video Tutorial"

The above is the detailed content of How to delete the current folder in php. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
php
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