ZetCode

PHP is_readable 函数

最后修改于 2025 年 4 月 3 日

PHP is_readable 函数用于检查文件是否存在且可读。在文件操作中,验证访问权限至关重要。

基本定义

is_readable 函数检查文件是否存在且具有读取权限。如果文件存在且可读,则返回 true,否则返回 false。

语法:is_readable(string $filename): bool。该函数在一个调用中同时检查文件的存在性和读取权限。

基本的 is_readable 示例

此示例展示了 is_readable 检查文件的最简单用法。

basic_is_readable.php
<?php

declare(strict_types=1);

$file = "data.txt";
$readable = is_readable($file);

echo $readable ? "File is readable" : "File is not readable";

这会检查 "data.txt" 是否存在且可读。该函数返回一个布尔值,我们可以在条件语句中使用它。

检查绝对路径

is_readable 也适用于绝对文件路径。

absolute_path.php
<?php

declare(strict_types=1);

$file = "/var/www/html/config.ini";
$readable = is_readable($file);

if ($readable) {
    echo "Config file is readable";
} else {
    echo "Cannot read config file";
}

此示例检查特定的绝对路径。该函数会验证文件的存在以及当前用户的读取权限。

检查目录可读性

该函数还可以检查目录是否可读。

directory_check.php
<?php

declare(strict_types=1);

$dir = "/var/www/uploads";
$readable = is_readable($dir);

echo $readable ? "Directory is readable" : "Cannot read directory";

这会检查目录 "/var/www/uploads" 是否可读。请注意,目录可读性在权限方面与文件可读性不同。

检查远程文件

is_readable 可以通过适当的 URL 包装器检查远程文件的可读性。

remote_file.php
<?php

declare(strict_types=1);

$url = "https://example.com/data.json";
$readable = is_readable($url);

if ($readable) {
    $content = file_get_contents($url);
    echo "Fetched content";
} else {
    echo "Cannot access remote file";
}

这会检查远程文件的可读性。请注意,为了正常工作,必须在 PHP 中启用 URL 包装器。

检查多个文件

我们可以在循环中使用 is_readable 来检查多个文件。

multiple_files.php
<?php

declare(strict_types=1);

$files = ["file1.txt", "file2.txt", "file3.txt"];

foreach ($files as $file) {
    if (is_readable($file)) {
        echo "$file is readable\n";
    } else {
        echo "$file is not readable\n";
    }
}

此示例检查数组中的多个文件。该函数会针对每个文件进行调用,单独返回其可读性状态。

边缘情况

is_readable 在某些边缘情况下具有特定的行为。

edge_cases.php
<?php

declare(strict_types=1);

$file1 = "";
$file2 = "nonexistent.txt";
$file3 = "/root/secret.txt";

var_dump(is_readable($file1)); // bool(false)
var_dump(is_readable($file2)); // bool(false)
var_dump(is_readable($file3)); // depends on permissions

空路径始终返回 false。不存在的文件返回 false。除非脚本具有适当的权限,否则根目录拥有的文件返回 false。

最佳实践

来源

PHP is_readable 文档

本教程通过实际示例介绍了 PHP is_readable 函数,展示了其在不同场景下的用法。

作者

我叫 Jan Bodnar,是一位充满热情的程序员,拥有丰富的编程经验。我从 2007 年开始撰写编程文章。迄今为止,我已撰写了 1400 多篇文章和 8 本电子书。我在编程教学方面拥有十多年的经验。

列出 所有 PHP 文件系统函数