Backend Development 3 min read

Understanding PHP's file_exists() Function: Return Values, Parameters, Usage Examples, and Best Practices

This article explains PHP's file_exists() function, detailing its boolean return value, single path parameter, practical code examples for checking files and directories, and important usage considerations such as path handling and its limitation to existence checks only.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Understanding PHP's file_exists() Function: Return Values, Parameters, Usage Examples, and Best Practices

The PHP file_exists() function checks whether a file or directory exists, returning a boolean true if it does and false otherwise.

Return Value

The function returns a boolean value: true when the specified path exists, false otherwise.

Parameters

It accepts a single parameter—the path to the file or directory, which can be relative to the current working directory or an absolute path.

Usage Examples

Check if a file exists

<code>$file = 'example.txt';
if (file_exists($file)) {
    echo "文件存在";
} else {
    echo "文件不存在";
}
</code>

This script outputs "文件存在" if example.txt is present in the current directory, otherwise it outputs "文件不存在".

Check if a directory exists

<code>$dir = 'example';
if (file_exists($dir)) {
    echo "目录存在";
} else {
    echo "目录不存在";
}
</code>

The script reports the existence of the example directory similarly.

Precautions

The function only determines existence; it does not check readability, writability, or executability.

When using relative paths, be aware of the current working directory; absolute paths are recommended to avoid errors.

file_exists() is fast, making it suitable for frequent existence checks.

Conclusion

file_exists() is a simple yet essential PHP function for verifying the presence of files or directories, returning a boolean result. Proper path handling and awareness of its limitations are important for reliable usage.

backendTutorialfile systemphp-functionsfile_exists
php中文网 Courses
Written by

php中文网 Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.