Home  >  Article  >  Backend Development  >  How to delete all files in a folder in php

How to delete all files in a folder in php

王林
王林Original
2020-08-18 15:49:243853browse

How to delete all files in a folder in php: first use the scandir() function to get all the files in a folder; then use the unlink() function to delete the files. If the deletion fails, Return false.

How to delete all files in a folder in php

scandir() function returns an array of files and directories in the specified directory.

(Recommended tutorial: php graphic tutorial)

Syntax:

scandir(directory,sorting_order,context);

unlink() function deletes files. Returns true if successful, false if failed.

Grammar:

unlink(filename,context)

(Learning video recommendation: php video tutorial)

Code implementation:

<?php
 //设置需要删除的文件夹
  $path = "./Application/Runtime/";
  //清空文件夹函数和清空文件夹后删除空文件夹函数的处理
  function deldir($path){
   //如果是目录则继续
   if(is_dir($path)){
    //扫描一个文件夹内的所有文件夹和文件并返回数组
   $p = scandir($path);
   foreach($p as $val){
    //排除目录中的.和..
    if($val !="." && $val !=".."){
     //如果是目录则递归子目录,继续操作
     if(is_dir($path.$val)){
      //子目录中操作删除文件夹和文件
      deldir($path.$val.&#39;/&#39;);
      //目录清空后删除空文件夹
      @rmdir($path.$val.&#39;/&#39;);
     }else{
      //如果是文件直接删除
      unlink($path.$val);
     }
    }
   }
  }
  }
 //调用函数,传入路径
 deldir($path);

The above is the detailed content of How to delete all files in a folder in php. 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