Hongmu Notes
Home Language Notes PHP: Delete all files and folders in the current directory.
Language Notes PHP

PHP: Delete all files and folders in the current directory.

PHP: Delete all files and folders in the current directory.

Below is a safe PHP script that scans and deletes all files and folders in the current working directory (excluding the script itself, unless otherwise noted). The script includes interactive confirmation to avoid misoperation.

<?php
/**
 * 递归删除目录下的所有内容(不包括当前目录本身)
 * 
 * @param string      $dir         要清理的目录路径
 * @param string|null $excludePath 需要排除的文件/目录的绝对路径(例如当前脚本自身)
 * @return bool 是否成功完成(部分失败也会继续,返回 false 表示有错误)
 */
function deleteAll(string $dir, ?string $excludePath = null): bool
{
    if (!is_dir($dir)) {
        fwrite(STDERR, "错误:{$dir} 不是一个目录\n");
        return false;
    }

    $success = true;
    $dh = @opendir($dir);
    if ($dh === false) {
        fwrite(STDERR, "错误:无法打开目录 {$dir}\n");
        return false;
    }

    while (($item = readdir($dh)) !== false) {
        if ($item === '.' || $item === '..') {
            continue;
        }

        $path = $dir . DIRECTORY_SEPARATOR . $item;

        // 如果设置了排除路径且当前路径与排除路径相同,则跳过
        // (注意:realpath() 会解析符号链接,可能导致排除行为与预期不符,此处保留原逻辑未改动)
        if ($excludePath !== null && realpath($path) === realpath($excludePath)) {
            echo "跳过排除项: {$path}\n";
            continue;
        }

        // 使用 lstat 一次性获取文件类型(避免多次 is_link/is_dir 调用)
        $stat = @lstat($path);
        if ($stat !== false) {
            // 确保常量可用(部分环境可能未预定义)
            if (!defined('S_IFMT')) define('S_IFMT', 0170000);
            if (!defined('S_IFDIR')) define('S_IFDIR', 0040000);
            if (!defined('S_IFREG')) define('S_IFREG', 0100000);
            if (!defined('S_IFLNK')) define('S_IFLNK', 0120000);

            $mode = $stat['mode'] & S_IFMT;

            if ($mode === S_IFLNK) {
                // 符号链接:只删除链接本身,不追踪目标
                if (unlink($path)) {
                    echo "已删除符号链接: {$path}\n";
                } else {
                    fwrite(STDERR, "错误:无法删除符号链接 {$path}\n");
                    $success = false;
                }
                continue;
            }

            if ($mode === S_IFDIR) {
                // 目录:递归删除内容,再删除空目录
                if (deleteAll($path, $excludePath)) {
                    if (rmdir($path)) {
                        echo "已删除目录: {$path}\n";
                    } else {
                        fwrite(STDERR, "错误:无法删除目录 {$path}(可能权限不足或非空)\n");
                        $success = false;
                    }
                } else {
                    $success = false;
                }
                continue;
            }

            if ($mode === S_IFREG) {
                // 普通文件
                if (unlink($path)) {
                    echo "已删除文件: {$path}\n";
                } else {
                    fwrite(STDERR, "错误:无法删除文件 {$path}\n");
                    $success = false;
                }
                continue;
            }

            // 其他类型(管道、套接字等),尝试删除
            if (unlink($path)) {
                echo "已删除特殊文件: {$path}\n";
            } else {
                fwrite(STDERR, "错误:无法删除特殊文件 {$path}\n");
                $success = false;
            }
        } else {
            // lstat 失败(如权限不足),回退到传统判断方式,尽可能删除
            if (is_link($path)) {
                if (unlink($path)) {
                    echo "已删除符号链接: {$path}\n";
                } else {
                    fwrite(STDERR, "错误:无法删除符号链接 {$path}\n");
                    $success = false;
                }
            } elseif (is_dir($path)) {
                if (deleteAll($path, $excludePath)) {
                    if (rmdir($path)) {
                        echo "已删除目录: {$path}\n";
                    } else {
                        fwrite(STDERR, "错误:无法删除目录 {$path}(可能权限不足或非空)\n");
                        $success = false;
                    }
                } else {
                    $success = false;
                }
            } else {
                if (unlink($path)) {
                    echo "已删除文件: {$path}\n";
                } else {
                    fwrite(STDERR, "错误:无法删除文件 {$path}\n");
                    $success = false;
                }
            }
        }
    }

    closedir($dh);
    return $success;
}

// 命令行运行检查
if (PHP_SAPI !== 'cli') {
    die("此脚本仅允许在命令行(CLI)模式下运行。\n");
}

// 获取当前工作目录(脚本执行时所在的目录)
$currentDir = getcwd();
if ($currentDir === false) {
    fwrite(STDERR, "错误:无法获取当前工作目录\n");
    exit(1);
}

echo "当前工作目录: {$currentDir}\n";

// 脚本自身的绝对路径
$selfPath = realpath(__FILE__);
$excludeSelf = false;

// 判断脚本自身是否位于当前工作目录下
if ($selfPath !== false && strpos($selfPath, $currentDir . DIRECTORY_SEPARATOR) === 0) {
    $excludeSelf = true;
    echo "注意:脚本自身位于当前目录,删除时将排除该文件: " . basename($selfPath) . "\n";
} else {
    echo "脚本自身不在当前目录,将删除当前目录下的所有内容。\n";
}

// 安全确认提示
echo "\n⚠️  警告:此操作将永久删除当前目录下的所有文件和文件夹,且不可恢复!\n";
echo "请输入 'yes' 确认执行: ";
$handle = fopen("php://stdin", "r");
$confirm = trim(fgets($handle));
fclose($handle);

if ($confirm !== 'yes') {
    echo "操作已取消。\n";
    exit(0);
}

echo "\n开始删除...\n";
$result = deleteAll($currentDir, $excludeSelf ? $selfPath : null);

if ($result) {
    echo "\n✅ 删除操作完成。\n";
    if ($excludeSelf && file_exists($selfPath)) {
        echo "注意:脚本自身未被删除,位于 {$selfPath}\n";
        echo "如需同时删除脚本自身,请手动执行: unlink('{$selfPath}');\n";
    }
} else {
    echo "\n❌ 删除过程中出现错误(部分文件/目录可能因权限等原因未被删除)。\n";
    exit(1);
}

security features

  • CLI only run: Prevent accidental triggering via web access.

  • Interactive confirmation:Must enter  yes  Deletion will be performed.

  • automatically exclude itself: If the script is located in the current working directory, it will be automatically skipped when deleting to avoid exceptions during operation.

  • Symbolic link security: Only delete the link itself, without tracking the link target, to prevent accidental deletion of important data.

  • Detailed log: Each deleted file/directory will be output, and error messages will be displayed to standard error.

  • Permission handling: If a file is deleted without permission, an error will be reported and the process will continue without interrupting the entire process.

微信赞赏

WeChat

支付宝赞赏

Alipay

✍️ Author: Hong Mu

webmaster · Thanks for reading, stay tuned for more exciting content

Author homepage View home page →

Related articles

PHP ob function record

PHP ob function record Language Notes PHP

Usage of the following three functions ob_get_contents(); ob_end_clean(); ob_start(); You can use these functions to buffer local files and execute local script code. Use ob_start() to save the output code into the buffer, and the page will not be displayed; then use ob_get_contents to get the data in the buffer. o…
👁 141
PHP preg

PHP preg Language Notes PHP

The preg_match_all function is used to perform a global regular expression match. preg_match_all() Syntax int preg_match_all ( string $pattern , string $subject [, array &$matches [, int $flags = PREG…
👁 169
Detailed explanation of PHP ternary operator and if

Detailed explanation of PHP ternary operator and if Language Notes PHP

Ternary operator condition ? Result 1 : Result 2 Explanation: The position in front of the question mark is the condition for judgment. If the condition is met, the result is 1, and if it is not met, the result is 2. This article compares and explains the ternary operator and if...else... in detail. I hope it will be helpful to everyone. Today when I was revising my paper online, I encountered a statement that I couldn’t understand: $if_summary = $row['IF_SUMMARY']=…
👁 189
PHP cast type

PHP cast type Language Notes PHP PHP collection PHP and mysql

Get the data type 1. If you want to check the value and type of an expression, use var_dump(). 2. If you just want to get an easy-to-read type expression for debugging, use gettype(). 3. To check a certain type, do not use gettype(), but use the is_type() function. Converting Strings to Numbers When a string is evaluated as a number, the result is determined according to the following rules...
👁 232

Recommended reading

(PC + WAP) Hardware and Machinery Marketing Website Template – 1019

(PC + WAP) Hardware and Machinery Marketing Website Template – 1019 Practical Collection pbootcms Template

A marketing-oriented PbootCMS website template for hardware and machinery equipment businesses, compatible with both PC and WAP devices. Featuring a professional marketing design style, this template is ideal for hardware and machinery enterprises to showcase their products and technological capabilities. It helps machinery manufacturing companies present their products online and attract targeted customer inquiries. Template Display | Installation Instructions | Website Backend: /admin.php | Username: admin | Password: admin | Extraction Password: www.4s5.cn...
👁 44
Responsive AI Chip Website Template 1018

Responsive AI Chip Website Template 1018 Practical Collection Yiyou template

An eyouCMS responsive website template designed for the artificial intelligence and AI chip industry. Its futuristic design style effectively showcases AI chip products, R&D initiatives, and real-world application scenarios. This template helps chip design companies build their brand image online and attract investment and customers. Template Display | Installation Instructions | Website Backend: /login.php | Username: admin | Password: admin | Related Articles: Summary of Common Installation Issues for YouyouCMS...
👁 65
(Adaptive Mobile Version) HTML5 Responsive LED Lighting Fixture PBootCMS Template – Download LED Lighting Website Source Code – 0459

(Adaptive Mobile Version) HTML5 Responsive LED Lighting Fixture PBootCMS Template – Download LED Lighting Website Source Code – 0459 Practical Collection pbootcms Template

A mobile-adaptive brand planning and high-end design PbootCMS website template. The design style is artistic and exquisite, and can display the entire brand case, creative design and business cases. It helps high-end design companies establish their brand image online and attract high-quality customers. Template display Installation instructions Website backend:/admin.php Account: admin Password: admin Unzip password: www.4s5.cn Related articles P…
👁 40
Responsive Resort Hotel Business Guest Room Website Template 0423

Responsive Resort Hotel Business Guest Room Website Template 0423 Practical Collection Yiyou template

An eyoucms responsive website template for resort hotels and business rooms. The design style is comfortable and high-end, and can display the hotel environment, room facilities, business services and online booking. Helps resort hotels attract tourists and business customers online. Template display Installation instructions Website backend: /login.php Account: admin Password: admin Related articles Summary of common problems in Yiyou CMS installation Yiyou CMS (E…
👁 38
(Adaptive Mobile Version) Responsive Hardware Foreign Trade English Website Template – 1020

(Adaptive Mobile Version) Responsive Hardware Foreign Trade English Website Template – 1020 Practical Collection pbootcms Template

A responsive五金 industry外贸 English PbootCMS website template supporting both PC and WAP devices. Its international and professional design style is ideal for hardware manufacturing enterprises to showcase their products and export advantages. It helps Chinese hardware companies present their brand image in the global market. Template Display | Installation Instructions | Website Backend: /admin.php | Username: admin | Password: admin | Extraction Password: www.4s5.cn | Related Articles: P...
👁 54
Responsive electronic component manufacturer website template 1019

Responsive electronic component manufacturer website template 1019 Practical Collection Yiyou template

This EyouCMS responsive template is ideal for electronic component manufacturers. Its modern, precision-oriented design effectively showcases electronic component products, technical specifications, and industry applications. It enables manufacturers to showcase their products online and attract customers within the electronics industry. Template Display | Installation Instructions | Website Backend: /login.php | Username: admin | Password: admin | Related Articles: Summary of Common Installation Issues for EyouCMS | EyouCMS...
👁 42