Home >Backend Development >PHP Problem >How to delete non-empty directories with php code

How to delete non-empty directories with php code

藏色散人
藏色散人Original
2022-10-31 10:23:411958browse

How to delete a non-empty directory with php code: 1. Create a PHP sample file; 2. Set the file encoding to utf8; 3. Delete the non-empty directory through a recursive function. The code is such as "function deldir ($dir){if(file_exists($dir)){$files=scandir($dir);foreach($files as $file){...}}".

How to delete non-empty directories with php code

The operating environment of this tutorial: Windows 7 system, PHP version 8.1, Dell G3 computer.

How to delete non-empty directories with php code?

The code is as follows:

<?php
header("Content-type: text/html; charset=utf-8");
 
$dir=&#39;mydir&#39;;
 
function deldir($dir){
    if(file_exists($dir)){
          $files=scandir($dir);
          foreach($files as $file){
                 if($file!=&#39;.&#39; && $file!=&#39;..&#39;){
                         $path=$dir.&#39;/&#39;.$file;
                         if(is_dir($path)){
                                 deldir($path);
                          }else{
                                  unlink($path);
                          }
                  }
           }
           rmdir($dir);
           return true;
    }else{
           return false;
    }
}
 
if(deldir($dir)){
      echo "目录删除成功!";
 }else{
      echo "没有目录!";
 }

PHP’s deletion of non-empty directories is actually implemented using recursive functions. PHP does not have a function to directly delete non-empty directories.

Recommended learning: "PHP Video Tutorial"

The above is the detailed content of How to delete non-empty directories with php code. For more information, please follow other related articles on the PHP Chinese website!

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