search
HomeBackend DevelopmentPHP TutorialPHP custom function rrmdir recursively deletes directories and files under directories

Example, PHP custom function rrmdir.

  1. //Recursively delete directories and files
  2. function rrmdir($dir) {
  3. if (is_dir($dir)) {
  4. $objects = scandir($dir);
  5. foreach ($objects as $object) {
  6. if ($object != “.” && $object != “..”) {
  7. if (filetype($dir.”/”.$object) == “dir”) rrmdir($dir.”/ ”.$object); else unlink($dir.”/”.$object);
  8. }
  9. }
  10. reset($objects);
  11. }
  12. }
Copy code

rmdir (PHP 4, PHP 5) rmdir — delete a directory Report a bug Description bool rmdir ( string $dirname ) Attempts to delete the directory specified by dirname. The directory must be empty and must have appropriate permissions. Returns TRUE on success, or FALSE on failure. Note: Since PHP 5.0.0 rmdir() can also be used with certain URL wrapping protocols. See the list of Supported Protocols and Wrappers to see which URL wrapping protocols rmdir() supports. Note: Support for Context was added in PHP 5.0.0. See the Stream function for a description of context. Note: When safe mode is enabled, PHP will check when executing a script whether the directory being scripted has the same UID (owner) as the script being executed. See mkdir() and unlink(). example:

  1. function rrmdir($dir) {
  2. if (is_dir($dir)) {
  3. $objects = scandir($dir);
  4. foreach ($objects as $object) {
  5. if ($object != "." && $object != "..") {
  6. if (filetype($dir."/".$object) == "dir") rrmdir($dir."/".$ object); else unlink($dir."/".$object);
  7. }
  8. }
  9. reset($objects);
  10. rmdir($dir);
  11. }
  12. }
  13. ?>
Copy code

This isn't my code, but just thought I would share, since it took me so long to find. This is a function to delete a folder, all sub-folders, and files in one clean move. Just tell it what directory you want deleted, in relation to the page that this function is executed. Then set $empty = true if you want the folder just emptied, but not deleted. If you set $empty = false, or just simply leave it out, the given directory will be deleted, as well.

Example:

  1. function deleteAll($directory, $empty = false) {
  2. if(substr($directory,-1) == "/") {
  3. $directory = substr($directory, 0,-1);
  4. }
  5. if(!file_exists($directory) || !is_dir($directory)) {
  6. return false;
  7. } elseif(!is_readable($directory)) {
  8. return false;
  9. } else {
  10. $directoryHandle = opendir($directory);
  11. while ($contents = readdir($directoryHandle)) {
  12. if($contents != '.' && $contents != '..') {
  13. $path = $ directory . "/" . $contents;
  14. if(is_dir($path)) {
  15. deleteAll($path);
  16. } else {
  17. unlink($path);
  18. } // bbs.it-home.org
  19. }
  20. }
  21. closedir($directoryHandle);
  22. if($empty == false) {
  23. if(!rmdir($directory)) {
  24. return false;
  25. }
  26. }
  27. return true;
  28. }
  29. }
  30. ?>
Copy code

A patch to previous script to make sure rights for deletion is set: example:

  1. //Delete folder function
  2. //Recursively delete directories and files
  3. function deleteDirectory($dir) {
  4. if (!file_exists($dir)) return true;
  5. if (!is_dir ($dir) || is_link($dir)) return unlink($dir);
  6. foreach (scandir($dir) as $item) {
  7. if ($item == '.' || $item == '. .') continue;
  8. if (!deleteDirectory($dir . "/" . $item)) {
  9. chmod($dir . "/" . $item, 0777);
  10. if (!deleteDirectory($dir . "/ " . $item)) return false;
  11. };
  12. }
  13. return rmdir($dir);
  14. }
  15. ?>
Copy code


Statement
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
PHP Performance Tuning for High Traffic WebsitesPHP Performance Tuning for High Traffic WebsitesMay 14, 2025 am 12:13 AM

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

Dependency Injection in PHP: Code Examples for BeginnersDependency Injection in PHP: Code Examples for BeginnersMay 14, 2025 am 12:08 AM

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

PHP Performance: is it possible to optimize the application?PHP Performance: is it possible to optimize the application?May 14, 2025 am 12:04 AM

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

PHP Performance Optimization: The Ultimate GuidePHP Performance Optimization: The Ultimate GuideMay 14, 2025 am 12:02 AM

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools