ZetCode

PHP file_exists 函数

最后修改于 2025 年 4 月 3 日

PHP的 file_exists 函数用于检查文件或目录是否存在。它对于文件操作至关重要,可以避免在访问不存在的文件时出现错误。

基本定义

file_exists 函数检查指定路径下的文件或目录是否存在。如果文件/目录存在,它返回 true;否则返回 false。

语法:file_exists(string $filename): bool。该函数同时支持文件和目录,并接受相对路径和绝对路径。

基本的 file_exists 示例

这展示了 file_exists 检查文件的最简单用法。

basic_file_exists.php
<?php

declare(strict_types=1);

$file = "example.txt";

if (file_exists($file)) {
    echo "The file $file exists";
} else {
    echo "The file $file does not exist";
}

这会检查当前目录下是否存在 "example.txt"。该函数返回一个布尔值,我们在条件语句中使用它。

检查绝对路径

file_exists 可以处理特定位置的绝对路径。

absolute_path.php
<?php

declare(strict_types=1);

$file = "/var/www/html/config.ini";

if (file_exists($file)) {
    echo "Configuration file found";
} else {
    echo "Configuration file missing";
}

这里我们检查一个绝对路径下的文件。这对于验证系统文件或特定位置的文件非常有用。

检查目录是否存在

该函数还可以检查目录是否存在,而不仅仅是文件。

directory_check.php
<?php

declare(strict_types=1);

$dir = "uploads";

if (file_exists($dir) && is_dir($dir)) {
    echo "The directory $dir exists";
} else {
    echo "The directory $dir does not exist";
}

我们将 file_existsis_dir 结合使用来专门检查目录。这确保我们检查的是目录,而不是文件。

URL 检查示例

file_exists 不能与 HTTP URL 一起使用 - 它仅适用于本地文件。

url_check.php
<?php

declare(strict_types=1);

$url = "https://example.com/image.jpg";

if (file_exists($url)) {
    echo "This will never be true for HTTP URLs";
} else {
    echo "Use file_get_contents or cURL for remote files";
}

这表明 file_exists 仅适用于本地文件系统路径。对于 URL,您需要使用像 file_get_contents 这样的不同函数。

权限考虑

文件权限会影响 file_exists 的结果。

permissions_check.php
<?php

declare(strict_types=1);

$restricted = "/etc/shadow";

if (file_exists($restricted)) {
    echo "File exists but you may not have access";
} else {
    echo "File may exist but is inaccessible";
}

即使文件存在,PHP也可能没有权限访问它。对于 Web 服务器用户无法读取的文件,该函数可能会返回 false。

最佳实践

来源

PHP file_exists 文档

本教程通过实际示例介绍了 PHP 的 file_exists 函数,展示了它在检查文件和目录存在性方面的用法。

作者

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

列出 所有 PHP 文件系统函数