TOC

PHP 文件操作

// 创建目录
if (!is_dir("mydirectory")) {
    mkdir("mydirectory");
} else {
    die("目录已存在");
}
// 创建多级目录
mkdir("path/to/my/directory", 0777, true);

// 删除目录
rmdir("newdir");

// 打开目录
$dir = opendir(".");

// 读目录
while($file = readdir($dir)) {
    echo $file . "<br />";
}

// 读目录 2
$directory = '/path/to/dir';
$iterator = new RecursiveIteratorIterator(
    new RecursiveDirectoryIterator($directory,
        RecursiveDirectoryIterator::SKIP_DOTS), // 忽略 . / ..
    RecursiveIteratorIterator::SELF_FIRST); // 深度优先
foreach ($iterator as $item) {
    if ($item->isDir()) {
        echo "目录: " . $item->getPath() . "\n";
    } else {
        echo "文件: " . $item->getPathname() . "\n";
    }
}

// 关闭目录
closedir($dir);

// 打开文件
$myfile = fopen("example.txt", "r");

// 读文件
$data = fread($myfile, filesize("example.txt"));

// 写文件
fwrite($myfile, "This is some text");

fclose($myfile);

// 读文件
$data = file_get_contents("example.txt");

// 写文件
file_put_contents("example.txt", "This is some text");

// 删除文件
unlink("example.txt");