在PHP编程中,目录遍历是一个常用的操作,它可以帮助我们读取目录中的文件和子目录。以下是一些实用的实例代码,帮助你轻松掌握PHP目录遍历。
实例1:遍历当前目录下的所有文件和子目录
<?php
function listDirectory($dir) {
if (!is_dir($dir)) {
return false;
}
$files = scandir($dir);
foreach ($files as $file) {
if ($file != "." && $file != "..") {
echo $file . "\n";
if (is_dir($dir . DIRECTORY_SEPARATOR . $file)) {
listDirectory($dir . DIRECTORY_SEPARATOR . $file);
}
}
}
}
listDirectory('path/to/your/directory');
?>
实例2:获取目录下的文件大小
<?php
function listDirectoryDetails($dir) {
if (!is_dir($dir)) {
return false;
}
$files = scandir($dir);
foreach ($files as $file) {
if ($file != "." && $file != "..") {
$path = $dir . DIRECTORY_SEPARATOR . $file;
$size = filesize($path);
echo $file . " - " . $size . " bytes\n";
if (is_dir($path)) {
listDirectoryDetails($path);
}
}
}
}
listDirectoryDetails('path/to/your/directory');
?>
实例3:复制目录及其内容
<?php
function copyDirectory($source, $destination) {
if (!is_dir($source)) {
return false;
}
if (!file_exists($destination)) {
mkdir($destination);
}
$files = scandir($source);
foreach ($files as $file) {
if ($file != "." && $file != "..") {
$sourceFile = $source . DIRECTORY_SEPARATOR . $file;
$destinationFile = $destination . DIRECTORY_SEPARATOR . $file;
if (is_dir($sourceFile)) {
copyDirectory($sourceFile, $destinationFile);
} else {
copy($sourceFile, $destinationFile);
}
}
}
}
copyDirectory('path/to/source/directory', 'path/to/destination/directory');
?>
实例4:删除目录及其内容
<?php
function deleteDirectory($dir) {
if (!is_dir($dir)) {
return false;
}
$files = scandir($dir);
foreach ($files as $file) {
if ($file != "." && $file != "..") {
$path = $dir . DIRECTORY_SEPARATOR . $file;
if (is_dir($path)) {
deleteDirectory($path);
} else {
unlink($path);
}
}
}
rmdir($dir);
}
deleteDirectory('path/to/directory/to/delete');
?>
实例5:搜索特定文件
<?php
function searchFile($dir, $filename) {
if (!is_dir($dir)) {
return false;
}
$files = scandir($dir);
foreach ($files as $file) {
if ($file == $filename) {
echo "Found: " . $dir . DIRECTORY_SEPARATOR . $file . "\n";
return true;
}
if (is_dir($dir . DIRECTORY_SEPARATOR . $file)) {
if (searchFile($dir . DIRECTORY_SEPARATOR . $file, $filename)) {
return true;
}
}
}
return false;
}
searchFile('path/to/search/directory', 'filename.txt');
?>
这些实例代码可以帮助你更好地理解如何在PHP中遍历目录。记得在实际应用中替换路径和文件名,以确保代码能够正确运行。
