0Pricing
PHP Academy · 课时

操作目录

使用 scandir 和 mkdir 列出、创建和删除目录。

操作目录 是 CoddyKit 上的免费 PHP Academy 课时。 这是第 3 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 PHP Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 PHP Academy 课程共包含 4 节课。

PHP 中的目录操作

PHP 提供了在服务器上列出、创建、导航和删除目录的函数:

  • scandir() — 列出目录内容
  • mkdir() — 创建目录
  • rmdir() — 删除空目录
  • glob() — 查找与模式匹配的文件

scandir()

列出目录中的所有文件和目录:

<?php
$entries = scandir('/var/www/html/uploads');

// scandir includes '.' and '..'
$entries = array_diff($entries, ['.', '..']);

foreach ($entries as $entry) {
    echo $entry . PHP_EOL;
}

glob() 模式匹配

glob() 返回与 shell 风格模式匹配的文件:

<?php
// Find all PHP files in a directory
$phpFiles = glob('/var/www/html/*.php');

// Recursively with GLOB_BRACE
$logs = glob('/var/log/{app,error,access}.log', GLOB_BRACE);

foreach ($phpFiles as $file) {
    echo basename($file) . PHP_EOL;
}

mkdir() 和权限

创建一个或多个嵌套目录:

<?php
$dir = '/var/www/uploads/2024/05';

// Create nested directories in one call:
if (!is_dir($dir)) {
    mkdir($dir, 0755, true);  // true = recursive
    echo "Created: $dir";
}

删除目录

rmdir() 只能删除空目录。要删除包含内容的目录,请使用递归函数:

<?php
function deleteDir(string $path): void {
    foreach (scandir($path) as $entry) {
        if ($entry === '.' || $entry === '..') continue;
        $full = $path . DIRECTORY_SEPARATOR . $entry;
        is_dir($full) ? deleteDir($full) : unlink($full);
    }
    rmdir($path);
}

deleteDir('/tmp/old_cache');

使用 DirectoryIterator 遍历目录

以 OO 方式遍历目录内容:

<?php
$dir = new DirectoryIterator('/var/www/html/images');

foreach ($dir as $info) {
    if ($info->isDot()) continue;
    echo $info->getFilename();
    echo ' (' . $info->getSize() . ' bytes)';
    echo PHP_EOL;
}

RecursiveDirectoryIterator

递归遍历目录树中的所有文件:

<?php
$iterator = new RecursiveIteratorIterator(
    new RecursiveDirectoryIterator('/var/www/src')
);

foreach ($iterator as $file) {
    if ($file->isDot()) continue;
    if ($file->getExtension() === 'php') {
        echo $file->getPathname() . PHP_EOL;
    }
}

getcwd 和 chdir

获取和更改当前工作目录:

<?php
$originalDir = getcwd();
echo 'Current: ' . $originalDir . PHP_EOL;

chdir('/var/www/html');
echo 'Changed to: ' . getcwd() . PHP_EOL;

// Restore
chdir($originalDir);
echo 'Restored: ' . getcwd() . PHP_EOL;

路径处理

使用可移植的常量和函数构建并解析文件路径:

<?php
// DIRECTORY_SEPARATOR = '/' on Unix, '\\' on Windows
$base    = '/var/www/app';
$subPath = 'uploads' . DIRECTORY_SEPARATOR . 'images';
$full    = $base . DIRECTORY_SEPARATOR . $subPath;

echo realpath($full);  // resolves symlinks

// __DIR__ is the directory of the current file
$configPath = __DIR__ . '/../config/settings.json';
echo realpath($configPath);

磁盘空间

检查可用磁盘空间和磁盘总空间:

<?php
$path = '/var/www';

$free  = disk_free_space($path);
$total = disk_total_space($path);
$used  = $total - $free;

echo 'Used: ' . round($used / 1024**3, 2) . ' GB';
echo 'Free: ' . round($free / 1024**3, 2) . ' GB';
echo 'Total: ' . round($total / 1024**3, 2) . ' GB';

SPL 临时目录

始终使用 sys_get_temp_dir(),以便在不同平台上找到正确的临时目录:

<?php
$tmpDir = sys_get_temp_dir();
echo 'Temp dir: ' . $tmpDir;

// Create a unique temporary directory
$uniqueDir = $tmpDir . DIRECTORY_SEPARATOR . 'myapp_' . uniqid();
mkdir($uniqueDir, 0700);

// ... use directory ...
// cleanup when done

快速检查

哪个 PHP 函数可以通过一次调用递归创建嵌套目录?

回顾:使用目录

目录操作:

  • scandir() — 列出内容(包括 . 和 ..)
  • glob() — 按模式查找文件
  • mkdir($path, 0755, true) — 递归创建
  • rmdir() — 删除空目录
  • 使用 RecursiveDirectoryIterator 进行深层遍历
  • 使用 __DIR__ 和 DIRECTORY_SEPARATOR 构建可移植路径

常见问题解答

「操作目录」课时是免费的吗?

是的 — 「操作目录」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 PHP Academy 课程的其余内容,请升级到 CoddyKit PRO。 PHP Academy 课程共包含 4 节课。

「操作目录」这节课中我会学到什么?

使用 scandir 和 mkdir 列出、创建和删除目录。 你通过在浏览器中直接运行的动手代码来练习 PHP Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 PHP Academy 需要有经验吗?

无需任何先前经验。CoddyKit 上的 PHP Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 3 节课,共 4 节。

「操作目录」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 PHP Academy 课中编写并运行代码吗?

能。每节 PHP Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 使用 PHP 读取文件
  2. 写入和追加文件内容
  3. 操作目录
  4. 处理文件上传
← 返回 PHP Academy