Using PHP is_file() to Check File Existence and Type
This article explains the PHP is_file() function, its syntax, parameters, return values, and provides clear code examples showing how to determine whether a given path points to an existing regular file and how to differentiate it from directories or special files.
In PHP programming, the is_file() function is a useful built‑in function that determines whether a given path or file exists and is a regular file.
First, the syntax of is_file() is:
bool is_file ( string $filename )The function accepts a single argument $filename , which specifies the path to be checked, and returns a boolean: true if the path exists and is a normal file, otherwise false .
Below is a simple code example demonstrating how to use is_file() to test whether a file exists:
<?php
$file = "/path/to/file.txt";
if (is_file($file)) {
echo "File exists!";
} else {
echo "File does not exist!";
}
?>In this example we define a file path in $file and then call is_file() . If the file is present, the script outputs "File exists!"; otherwise it outputs "File does not exist!".
Beyond checking existence, is_file() also verifies that the path refers to a regular file. If the path points to a directory or a special file (such as a device file or symbolic link), is_file() returns false .
The following example shows how to use is_file() to determine whether a path is a regular file:
<?php
$path = "/path/to/directory";
if (is_file($path)) {
echo "This is a regular file!";
} else {
echo "This is not a regular file!";
}
?>Here we set $path to a directory path and call is_file() . Because the path is a directory, the function returns false and the script outputs "This is not a regular file!".
It is important to note that is_file() only checks for regular files. To check whether a path is a directory, use the is_dir() function instead.
In summary, is_file() is a practical PHP function for verifying that a given path exists and is a normal file; understanding its usage helps developers handle file system checks reliably in their applications.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.