Hongmu Notes
Home Language Notes PHP function to delete all files and directories within a specified directory; allows for excluding certain files.
Language Notes PHP

PHP function to delete all files and directories within a specified directory; allows for excluding certain files.

PHP function to delete all files and directories within a specified directory; allows for excluding certain files.

I really cried!

After a lot of troubleshooting, I realized that the `glob` function was somewhat tricky to use – I couldn't retrieve the system's hidden files. After much effort, I discovered that there were other functions available for querying all files!

The `PHP` function `rm` removes all files and directories within a specified directory; it accepts two parameters: the directory to be deleted and an array of files that should not be deleted.

function deleteDirectory($directory, $excludes = []) {
    // 判断目录是否存在
    if (!is_dir($directory)) {
        throw new Exception("目录 $directory 不存在");
    }

    // 获取目录中的所有文件和目录
    $files = array_diff(scandir($directory), ['.', '..']);

    // 遍历所有文件和目录
    foreach ($files as $file) {
        $path = $directory . DIRECTORY_SEPARATOR . $file;
        // 如果是目录,递归处理子目录
        if (is_dir($path)) {
            deleteDirectory($path, $excludes);
            rmdir($path);
        }
        // 如果是文件,并且不在不需要删除的文件列表中,就删除文件
        elseif (is_file($path) && !in_array($file, $excludes)) {
            unlink($path);
        }
    }
}

This function has two parameters:$directory The directory to be deleted.$excludes The list of files that should not be deleted is an array. If the directory to be deleted does not exist, the function will throw an exception.

The function is used first. scandir The function retrieves all files and directories from the directory and uses them. array_diff Remove function ...This generates an array containing only file and directory names. Then, iterate through all files and directories; if a directory is encountered, recursively call the function itself to process the subdirectories and use it. rmdir Delete empty directories; if the item is a file and is not present in the list of files to be deleted, then proceed. unlink The function deletes a file.

Call Method

// 删除 /path/to/directory 目录下的所有文件和目录,但不删除 1.php 和 2.php
$directory = '/path/to/directory';
$excludes = ['1.php', '2.php'];
deleteDirectory($directory, $excludes);
微信赞赏

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

PHP batch replaces file names in specified folders

PHP batch replaces file names in specified folders Language Notes PHP

The following is a PHP function that can batch rename file names in a specified folder: 🔒 Hidden content: You can view the function after logging in batchRenameFiles($dir, $search, $replace) { $files = scandir($dir); // Get all files in the directory foreach ($files…
👁 235
(PC+WAP) FRP Environmental Protection Equipment Category – pbootCMS Website Template; Stainless Steel Website Source Code Download – 0068

(PC+WAP) FRP Environmental Protection Equipment Category – pbootCMS Website Template; Stainless Steel Website Source Code Download – 0068 Practical Collection pbootcms Template

A PbootCMS website template designed for the FRP (fiberglass-reinforced plastic) and stainless steel industries, compatible with both PC and WAP devices. Its industrial-style design effectively showcases the characteristics of FRP products and stainless steel materials. The template includes built-in product display and project case study modules, enabling environmental protection equipment manufacturers to quickly set up their official brand websites. Template Display | Installation Instructions | Website Backend: /admin.php | Username: admin | Password: admin...
👁 37
(Adaptive Mobile App) Single-Page Website Template – App Implementation Page 1001

(Adaptive Mobile App) Single-Page Website Template – App Implementation Page 1001 Practical Collection pbootcms Template

A single-page landing page template for PbootCMS websites, compatible with both PC and WAP devices. Featuring a modern, tech-driven design with a strong marketing focus, this template is ideal for high-conversion landing pages such as app promotions or software download pages. It enables app developers to quickly create promotional pages and attract users to download their apps. Template Preview | Installation Instructions | Website Backend: /admin.php | Username: admin | Password: admin | Extraction Password: www....
👁 33
Simple news and information website template – 0800

Simple news and information website template – 0800 Practical Collection Yiyou template

An EyouCMS template designed for clean, news-focused websites. Its minimalist, information-flow design is ideal for publishing news articles, industry updates, trending topics, and in-depth reports. This template helps news websites attract online readers and build media influence. Template Display | Installation Instructions | Website Backend: /login.php | Username: admin | Password: admin | Related Articles: Summary of Common Installation Issues for EyouCMS | EyouCMS (Ey...
👁 54
jquery click to jump to the top of the web page

jquery click to jump to the top of the web page Language Notes JavaScript

You can use jQuery to jump to the top of the web page after clicking on an element. The following is a simple implementation method: $(document).ready(function() { // Listen to the click event of the element $('#my-element').click(function() { // Scroll to the top $('html, body').an…
👁 205
(PC + WAP) Lifestyle Information Encyclopedia Portal Website – pbootCMS Template; Pink Lifestyle Portal Website Source Code Download – 0069

(PC + WAP) Lifestyle Information Encyclopedia Portal Website – pbootCMS Template; Pink Lifestyle Portal Website Source Code Download – 0069 Practical Collection pbootcms Template

This PbootCMS template features a pink color scheme and is ideal for lifestyle news, encyclopedia-style content, and portal websites; it supports both PC and WAP devices. Its fresh and sweet design makes it perfect for female-oriented or lifestyle service content platforms. This template helps information portals or individual bloggers create a rich, user-friendly information-sharing platform. Template Display | Installation Instructions | Website Backend: /admin.php | Username: admin | Password: adm...
👁 54