Master PHP’s is_file(): Quick Guide to Checking File Existence

This article explains how the PHP is_file() function works, shows proper usage with absolute and relative paths, highlights important caveats such as its inability to check directories or symlink targets, and provides practical code examples for safe file handling.

php Courses
php Courses
php Courses
Master PHP’s is_file(): Quick Guide to Checking File Existence
is_file()

is a basic and useful PHP function that checks whether a specified file exists.

The function takes a file path (absolute or relative) as its argument and returns true if the file exists, otherwise false.

Example usage:

$file = '/path/to/myfile.txt';
if (is_file($file)) {
    echo "文件存在";
} else {
    echo "文件不存在";
}

The path can be absolute or relative to the script’s directory; using paths relative to the script’s root is recommended.

Note that is_file() only checks files, not directories. To test a directory, use is_dir().

Because the return value is boolean, it is typically used in if statements, e.g., before calling file_get_contents() to read a file.

$file = '/path/to/myfile.txt';
if (is_file($file)) {
    $content = file_get_contents($file);
} else {
    echo "文件不存在";
}

Additional considerations: if the argument is a symbolic link, is_file() returns true only when the target file exists; it always returns false for directories.

In summary, mastering is_file() helps PHP developers avoid errors when handling file operations.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

file-handlingis_file
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

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.