PHP递归获取目录内容readDir,递归删除rmdir

<pre name="code" class="php"><?php
/**
 * @param $path 需要读取的目录内容
 */
function readDirs($path, $deep=0) {
	//打开,读取
	$handle = openDir($path);
	//循环获得文件
	while(false !== $file = readDir($handle)) {
		//是不是伪目录 ., ..,是的话不处理
		if ($file == '.' || $file == '..') continue;


		echo str_repeat(' ', $deep*4), $file,'<br>';
		//判断该文件是否为目录
		if(is_dir($path . '/' . $file)) {
			//是目录,递归的获取
			readDirs($path . '/' . $file, $deep+1);
		}
	}
	closeDir($handle);
}
 


将获取的目录保存起来,以便之后使用代码如下

/**
 * @param $path 需要读取的目录内容
 *
 * @return array 很多维数组
 */
function readDirs($path, $deep=0) {
	$children = array();
	//打开,读取
	$handle = openDir($path);
	//循环获得文件
	while(false !== $file = readDir($handle)) {
		//是不是伪目录 ., ..,是的话不处理
		if ($file == '.' || $file == '..') continue;
		//记录当前文件信息的数组
		$file_info['name']=$file;//文件名
		//判断该文件是否为目录
		if(is_dir($path . '/' . $file)) {
			//是目录,递归的获取
			$file_info['type'] = 'dir';
			$file_info['children'] = readDirs($path . '/' . $file, $deep+1);
		} else {
			$file_info['type'] = 'file';
		}
		$children[] = $file_info;
	}
	closeDir($handle);
	return $children;
}

/**
 * @param $path 删除需要目录
 */
function rmDirs($path) {
	//打开,读取
	$handle = openDir($path);
	//循环获得文件
	while(false !== $file = readDir($handle)) {
		//是不是伪目录 ., ..,是的话不处理
		if ($file == '.' || $file == '..') continue;

		//判断该文件是否为目录
		if(is_dir($path . '/' . $file)) {
			//是目录,递归的获取
			rmDirs($path . '/' . $file);
		} else {
			//文件
			unlink($path . '/' . $file);//unlink删除文件
		}
	}
	closeDir($handle);
	return rmdir($path);
}
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值