ZetCode

PHP is_file 函数

最后修改于 2025 年 4 月 3 日

PHP is_file 函数检查一个路径是否为普通文件。 在进行文件操作之前,它对于验证文件是否存在和文件类型很有用。

基本定义

如果文件名存在并且是一个普通文件,则 is_file 函数返回 true。对于目录、符号链接或不存在的路径,它返回 false。

语法:is_file(string $filename): bool。该函数缓存结果,以便在重复检查同一文件时获得更好的性能。

基本的 is_file 示例

这展示了 is_file 的最简单用法,用于检查文件。

basic_is_file.php
<?php

declare(strict_types=1);

$path = "/var/www/html/index.php";

if (is_file($path)) {
    echo "The path points to a regular file.";
} else {
    echo "The path does not point to a regular file.";
}

这检查 "/var/www/html/index.php" 是否为普通文件。 该函数仅对实际文件返回 true,而不是目录或特殊文件。

检查相对路径

is_file 使用基于当前目录的相对路径。

relative_path.php
<?php

declare(strict_types=1);

$path = "config.ini";

if (is_file($path)) {
    echo "Found config file in current directory.";
} else {
    echo "Config file not found in current directory.";
}

这检查当前工作目录中是否存在 "config.ini"。 请记住,PHP 的当前目录可能与脚本的位置不同。

检查多个文件

您可以使用 is_file 验证数组中的多个文件。

multiple_files.php
<?php

declare(strict_types=1);

$files = [
    "/var/log/apache2/access.log",
    "/var/log/apache2/error.log",
    "/var/log/apache2/other_vhosts_access.log"
];

foreach ($files as $file) {
    echo $file . " is " . (is_file($file) ? "a file" : "not a file") . "\n";
}

这遍历一个日志文件数组并检查每一个文件。三元运算符通过将布尔值转换为文本使输出更具可读性。

与 file_exists 的比较

is_filefile_exists 在特异性上有所不同。

compare_file_exists.php
<?php

declare(strict_types=1);

$path = "/var/www/html/uploads";

$fileExists = file_exists($path);
$isFile = is_file($path);

echo "file_exists: " . ($fileExists ? "true" : "false") . "\n";
echo "is_file: " . ($isFile ? "true" : "false") . "\n";

对于目录,file_exists 返回 true,而 is_file 返回 false。当您特别需要一个普通文件时,请使用 is_file

检查符号链接

is_file 跟踪符号链接以检查目标文件。

symlink_check.php
<?php

declare(strict_types=1);

$symlink = "/var/www/html/current";
$target = "/var/www/html/releases/v1.2.3";

if (is_file($symlink)) {
    echo "The symlink points to a regular file.";
} else {
    echo "The symlink does not point to a regular file.";
}

这检查符号链接的目标是否为普通文件。该函数会自动取消引用符号链接以检查实际文件。

最佳实践

来源

PHP is_file 文档

本教程涵盖了 PHP is_file 函数,并提供了实际示例,展示了它在不同场景中的用法。

作者

我的名字是 Jan Bodnar,我是一位充满激情的程序员,拥有丰富的编程经验。自 2007 年以来,我一直在撰写编程文章。到目前为止,我撰写了 1,400 多篇文章和 8 本电子书。我拥有超过十年的编程教学经验。

列出 所有 PHP 文件系统函数