Hongmu Notes
Home Language Notes PHP – Delete a specified directory
Language Notes PHP

PHP – Delete a specified directory

PHP – Delete a specified directory

In PHP, you can use the ` unlink()` function to delete a directory. rmdir Function: This function deletes a specified directory; however, if the directory is not empty, it cannot be deleted – the files and subdirectories within it must first be removed.

Below is how to use it. rmdir Example code for deleting a specified directory using a function

$dir = '/path/to/dir'; // 要删除的目录路径
if (is_dir($dir)) { // 如果目录存在
    $files = glob($dir . '/*'); // 获取目录下的所有文件和子目录
    foreach ($files as $file) {
        if (is_file($file)) { // 如果是文件则直接删除
            unlink($file);
        } else { // 如果是子目录则递归调用自身
            deleteDir($file);
        }
    }
    rmdir($dir); // 删除目录
}

The above code is used. is_dir Check whether the directory exists – Use. glob The `get_all_files_and_subdirectories` function retrieves all files and subdirectories from a given directory; use it accordingly. unlink The function deletes a file using a recursive call. deleteDir Delete subdirectory; use at the end. rmdir Delete directory.

Please note that the deletion operation is irreversible; therefore, please proceed with caution.

<?php
// 定义要删除的文件夹路径
$dir = "/path/to/directory";

// 递归删除非空文件夹
function deleteDirectory($dir) {
    if (!file_exists($dir)) {
        return true;
    }

    if (!is_dir($dir)) {
        return unlink($dir);
    }

    foreach (scandir($dir) as $item) {
        if ($item == '.' || $item == '..') {
            continue;
        }

        if (!deleteDirectory($dir . DIRECTORY_SEPARATOR . $item)) {
            return false;
        }
    }

    return rmdir($dir);
}

// 调用递归函数删除文件夹
if (deleteDirectory($dir)) {
    echo "文件夹删除成功";
} else {
    echo "文件夹删除失败";
}
?>

 

微信赞赏

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…
👁 143
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']=…
👁 191
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

Beauty, Cosmetics & Weight Loss Website Templates – 1047

Beauty, Cosmetics & Weight Loss Website Templates – 1047 Practical Collection Yiyou template

An EyouCMS website template designed for the beauty, cosmetics, and weight loss industries. Its stylish and sophisticated design is ideal for showcasing beauty services, makeup and styling services, weight loss programs, and brand stories. This template helps beauty and weight loss businesses attract female customers online and enhance their brand awareness. Template Display | Installation Instructions | Website Backend: /login.php | Username: admin | Password: admin | Related Articles: Summary of Common Installation Issues for EyouCMS | Eyou...
👁 39
Responsive ceramic tableware and tea set website template – 0010

Responsive ceramic tableware and tea set website template – 0010 Practical Collection Yiyou template

This EyouCMS responsive template is ideal for ceramic tableware and tea set manufacturers. Its elegant and sophisticated design beautifully highlights the craftsmanship and aesthetic appeal of ceramic products. It is perfect for ceramic brands and tableware/tea set distributors to create a professional brand website to showcase their product ranges and design styles. Template Demo | Installation Guide | Website Backend: /login.php | Username: admin | Password: admin | Related Articles: Summary of Common Installation Issues for EyouCMS | Eyou...
👁 46
(Adaptive Mobile Version) HTML5 responsive toy and anime-themed website PBootCMS template – Download source code for a cartoon doll website: 0189

(Adaptive Mobile Version) HTML5 responsive toy and anime-themed website PBootCMS template – Download source code for a cartoon doll website: 0189 Practical Collection pbootcms Template

This adaptive, mobile-friendly HTML5 responsive toy and anime-themed PbootCMS website template features a cartoon-style design. Its lively and charming aesthetic makes it ideal for showcasing toy products, anime IPs, and other content geared towards children. It helps toy brands or anime companies attract young consumers and parents online. Template Preview | Installation Instructions | Website Backend: /admin.php | Username: admin | Password: admin | Extraction Password: ww...
👁 59
Medical Skin Health Website Template 1048

Medical Skin Health Website Template 1048 Practical Collection Yiyou template

This EyouCMS template is ideal for the healthcare and dermatology sectors, featuring a professional and clean design that effectively showcases skin care services, health management solutions, expert teams, and successful case studies. It helps dermatology clinics attract patients online and enhance their brand professionalism. Template Preview | Installation Instructions | Website Backend: /login.php | Username: admin | Password: admin | Related Articles: Summary of Common Installation Issues for EyouCMS | EyouCMS...
👁 59
Responsive large-scale electronics enterprise group website template 0011

Responsive large-scale electronics enterprise group website template 0011 Practical Collection Yiyou template

An eYouCMS responsive website template designed for large electronics enterprise groups. Featuring a modern and sophisticated design style along with comprehensive functional modules, it effectively showcases the group's organizational structure, business segments, product portfolio, and corporate culture. It is an excellent choice for large electronics and technology companies looking to build their official brand websites. Template Preview | Installation Instructions | Website Backend: /login.php | Username: admin | Password: admin | Related Articles: Common Installation Issues for eYouCMS...
👁 47
(Adaptive mobile version) HTML5 responsive eco-friendly wastewater treatment equipment PBootCMS website template; Vacuum pump equipment website source code download – 0190

(Adaptive mobile version) HTML5 responsive eco-friendly wastewater treatment equipment PBootCMS website template; Vacuum pump equipment website source code download – 0190 Practical Collection pbootcms Template

An adaptive, mobile-friendly HTML5 responsive website template for environmental wastewater treatment equipment – PbootCMS. This template features a modern, professional design style ideal for showcasing wastewater treatment technologies, equipment products, and project cases. It enables environmental equipment companies to present their solutions online and attract municipal and industrial clients. Template Overview | Installation Instructions | Website Backend: /admin.php | Username: admin | Password: admin | Extraction Password: www....
👁 55