## PHP实战:轻松掌握目录遍历的10个实用代码示例
在PHP开发中,目录遍历是一个基础但又非常实用的技能。无论是构建文件管理系统,还是需要从目录中提取文件信息,目录遍历都能派上大用场。以下将为你介绍10个PHP目录遍历的实用代码示例,帮助你轻松掌握这一技能。
### 示例1:遍历当前目录下的所有文件和子目录
```php
<?php
function list_files($dir) {
$files = array();
if (is_dir($dir)) {
if ($dh = opendir($dir)) {
while (($file = readdir($dh)) !== false) {
if ($file != "." && $file != "..") {
$files[] = $file;
}
}
closedir($dh);
}
}
return $files;
}
$directory = './path/to/directory';
print_r(list_files($directory));
?>
示例2:遍历目录并包含子目录下的所有文件
<?php
function list_files_recursive($dir) {
$files = array();
if (is_dir($dir)) {
if ($dh = opendir($dir)) {
while (($file = readdir($dh)) !== false) {
if ($file != "." && $file != "..") {
$fullpath = $dir . DIRECTORY_SEPARATOR . $file;
if (is_dir($fullpath)) {
$files = array_merge($files, list_files_recursive($fullpath));
} else {
$files[] = $fullpath;
}
}
}
closedir($dh);
}
}
return $files;
}
$directory = './path/to/directory';
print_r(list_files_recursive($directory));
?>
示例3:检查文件是否存在
<?php
$filePath = './path/to/file.txt';
if (file_exists($filePath)) {
echo "文件存在。";
} else {
echo "文件不存在。";
}
?>
示例4:获取文件信息
<?php
$filePath = './path/to/file.txt';
if (file_exists($filePath)) {
$fileInfo = filesize($filePath);
echo "文件大小:{$fileInfo} 字节。";
} else {
echo "文件不存在。";
}
?>
示例5:删除文件
<?php
$filePath = './path/to/file.txt';
if (file_exists($filePath)) {
if (unlink($filePath)) {
echo "文件删除成功。";
} else {
echo "文件删除失败。";
}
} else {
echo "文件不存在。";
}
?>
示例6:读取目录下的文件列表到数组
<?php
$directory = './path/to/directory';
$fileList = scandir($directory);
print_r($fileList);
?>
示例7:复制文件
<?php
$sourcePath = './path/to/source/file.txt';
$destPath = './path/to/destination/file.txt';
if (copy($sourcePath, $destPath)) {
echo "文件复制成功。";
} else {
echo "文件复制失败。";
}
?>
示例8:重命名文件
<?php
$oldName = './path/to/old/file.txt';
$newName = './path/to/new/file.txt';
if (rename($oldName, $newName)) {
echo "文件重命名成功。";
} else {
echo "文件重命名失败。";
}
?>
示例9:移动文件到新位置
<?php
$sourcePath = './path/to/source/file.txt';
$destPath = './path/to/destination/file.txt';
if (rename($sourcePath, $destPath)) {
echo "文件移动成功。";
} else {
echo "文件移动失败。";
}
?>
示例10:递归创建目录
<?php
function create_dir($dir) {
if (!file_exists($dir)) {
if (!mkdir($dir, 0777, true)) {
die('Failed to create directories...');
}
}
}
$directory = './path/to/new/directory';
create_dir($directory);
?>
这些代码示例涵盖了PHP目录遍历的基本操作,从列出目录内容到处理文件属性。通过学习和实践这些示例,你将能够轻松地在你的PHP项目中应用目录遍历的功能。
