首页 > 技术文章 > PHP之基本目录操作

gaogzhen 2019-05-15 11:07 原文

一、创建目录

mkdir ($pathname, $mode = 0777, $recursive = false, $context = null)

  • $pathname: 目录路径
  • $mode : 目录权限
  • $recursive : 递归

二、删除目录

rmdir ($dirname, $context = null)

  • $dirname: 目录路径

三、读取目录内容

步骤:

3.1、打开目录,获取文件句柄

$fin = opendir($path);
var_dump($fin);
resource(2) of type (stream)

3.2、读取内容

while (false !== ($dir_name = readdir($dir_handler)))

如果读取内容不为空,继续读取

3.3、关闭文件句柄

closedir($dir_handler);
用于释放资源

四、递归之目录结构

4.1、读取目录结构

4_1代码:

$path = '../secshop_upload';//目录或者文件路径

recursiveDir($path);
function recursiveDir($pathname, $depth = 0) {
	$dir_handler = opendir($pathname);
	while (false !== ($dir_name = readdir($dir_handler))) {
	if ($dir_name == '.' || $dir_name == '..') continue;
		echo str_repeat('-', $depth).$dir_name . '<br />';
		if (is_dir($pathname.DIRECTORY_SEPARATOR.$dir_name)) recursiveDir($pathname.DIRECTORY_SEPARATOR.$dir_name, $depth +1);
	}
	closedir($dir_handler);
}

结果:
application
-back
--controller
---GoodsController.class.php
---LoginController.class.php
---ManageController.class.php
---PlatformController.class.php
--model
---AdminModel.class.php
---GoodsModel.class.php
--view
...

4.2、获取目录结构嵌套数组

$path = '..'.DIRECTORY_SEPARATOR.'secshop_upload';//目录或者文件路径

$arr = recursiveDir($path);
echo '<pre>';
var_dump($arr);
echo '</pre>';


/**
 * @param $pathname     目录路径
 * @return array        嵌套数组:递归遍历目录内容存入数组
 */
function recursiveDir($pathname) {
	$nested_arr = array();//存放当前目录下内容 f
	$index = 0;
	$dir_handler = opendir($pathname);//打开目录,获取文件句柄
	while (false !== ($dir_name = readdir($dir_handler))) {//循环读取目录内容

		if ($dir_name == '.' || $dir_name == '..') continue;//'.' 和'..'为逻辑目录
		$nested_arr[$index]['filename'] = $dir_name;//‘filename'目录或者文件名
		if (is_dir($pathname.DIRECTORY_SEPARATOR.$dir_name)) {
			$nested_arr[$index]['type'] = 'DIR';//type 类型: DIR 目录;FILE 文件
			//nested 子目录内容数组
			$nested_arr[$index]['nested'] = recursiveDir($pathname.DIRECTORY_SEPARATOR.$dir_name);
		}else {
			$nested_arr[$index]['type'] = 'FILE';
		}
		$index++;
	}
	closedir($dir_handler);//关闭文件句柄,是否资源
	return $nested_arr;//目录内容数组返回
}

结果:
array(6) {
[0]=>
array(3) {
["filename"]=>
string(11) "application"
["type"]=>
string(3) "DIR"
["nested"]=>
array(4) {
[0]=>
array(3) {
["filename"]=>
string(4) "back"
["type"]=>
string(3) "DIR"
["nested"]=>
array(3) {
[0]=>
array(3) {
["filename"]=>
string(10) "controller"
["type"]=>
string(3) "DIR"
["nested"]=>
array(4) {
[0]=>
array(2) {
["filename"]=>
string(25) "GoodsController.class.php"
["type"]=>
string(4) "FILE"
}

五、中文路径

iconv ($in_charset, $out_charset, $str)

  • $in_charset: The input charset
  • $out_charset: output charset
  • $str : 要转换的字符串
    通过字符集转换,解决乱码等问题

推荐阅读