Home >Backend Development >PHP Tutorial >How to delete all directories and files in a specified directory with PHP_PHP Tutorial

How to delete all directories and files in a specified directory with PHP_PHP Tutorial

WBOY
WBOYOriginal
2016-07-13 10:05:58820browse

How to delete all directories and files in a specified directory in PHP

This article mainly introduces how to delete all directories and files in a specified directory in PHP through custom functions delFile implements the function of recursive deletion, which has certain reference value. Friends who need it can refer to it

The example in this article describes how to delete all directories and files in the specified directory with PHP. Share it with everyone for your reference. The specific implementation method is as follows:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

/*

*

* 删除指定目录中的所有目录及文件(或者指定文件)

* 可扩展增加一些选项(如是否删除原目录等)

* 删除文件敏感操作谨慎使用

* @param $dir 目录路径

* @param array $file_type指定文件类型

*/

function delFile($dir,$file_type='') {

if(is_dir($dir)){

$files = scandir($dir);

//打开目录 //列出目录中的所有文件并去掉 . 和 ..

foreach($files as $filename){

if($filename!='.' && $filename!='..'){

if(!is_dir($dir.'/'.$filename)){

if(empty($file_type)){

unlink($dir.'/'.$filename);

}else{

if(is_array($file_type)){

//正则匹配指定文件

if(preg_match($file_type[0],$filename)){

unlink($dir.'/'.$filename);

}

}else{

//指定包含某些字符串的文件

if(false!=stristr($filename,$file_type)){

unlink($dir.'/'.$filename);

}

}

}

}else{

delFile($dir.'/'.$filename);

rmdir($dir.'/'.$filename);

}

}

}

}else{

if(file_exists($dir)) unlink($dir);

}

}

delFile(dirname(__FILE__),'html');

1 2

3

4 5

67 8 9 10 11 12
13
14
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
I hope this article will be helpful to everyone’s PHP programming design. http://www.bkjia.com/PHPjc/961079.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/961079.htmlTechArticleHow to delete all directories and files in the specified directory using PHP. This article mainly introduces how to delete all directories and files in the specified directory using PHP. All directory and file methods implement recursion through the custom function delFile...
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