Master PHP’s is_file(): Check File Existence and Type with Simple Code
This article explains PHP’s is_file() function, detailing its syntax, parameters, return values, and practical examples for checking whether a path points to an existing regular file, while also noting its limitation compared to is_dir() for directory checks.
In PHP programming, the is_file() function is a very useful function. It is used to determine whether a given path or file exists and is a regular file. This article introduces how to use is_file() and provides concrete code examples.
Syntax
bool is_file ( string $filename )The function accepts one parameter $filename, which specifies the file path to check. It returns a boolean: true if the path points to an existing regular file, otherwise false.
Example: checking if 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 $file and use is_file() to check its existence, outputting the appropriate message.
Besides checking existence, is_file() can determine whether a path is a regular file. If the path is a directory or a special file (e.g., device file or symbolic link), is_file() returns false.
Example: checking if 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 define a path $path and use is_file() to verify whether it is a regular file, printing the corresponding message.
Note that is_file() is only for regular files. To check whether a path is a directory, use the is_dir() function.
In summary, is_file() is a practical PHP function for determining if a path or file exists and is a regular file. Understanding its usage enables flexible file handling in development.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
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.
