Using PHP file_exists() to Check File and Directory Existence
This article explains PHP's file_exists() function, its syntax, parameters, return values, and provides example code for checking both files and directories, along with important usage notes and best practices in web development.
In PHP programming, it is common to need to verify whether a file or directory exists before performing further operations; the file_exists() function serves this purpose.
Syntax
bool file_exists ( string $filename )Parameter
$filename : the path of the file or directory to be checked.
Return Value
The function returns true if the file or directory exists, and false otherwise.
Example
The following example demonstrates how to use file_exists() to check a file and a directory.
<?php
// Check if a file exists
$file = 'example.txt';
if (file_exists($file)) {
echo "文件存在。"; // File exists.
} else {
echo "文件不存在。"; // File does not exist.
}
// Check if a directory exists
$dir = 'example_dir';
if (file_exists($dir) && is_dir($dir)) {
echo "目录存在。"; // Directory exists.
} else {
echo "目录不存在。"; // Directory does not exist.
}
?>In the example, a variable $file holds the file path and file_exists() determines its existence, outputting an appropriate message. Similarly, a variable $dir holds a directory path; the code uses both file_exists() and is_dir() to confirm that the path exists and is a directory before printing the result.
Important Notes
file_exists() can check both local filesystem entries and remote files by specifying a URL.
The function does not differentiate between files and directories; it returns true for either if the path exists.
It only reports existence and does not impose any access restrictions.
Before using file_exists() , it is advisable to check readability or writability with is_readable() or is_writable() to avoid permission‑related errors.
Summary
The file_exists() function is a fundamental PHP tool for determining the presence of files or directories. It returns a boolean value and can be combined with other file‑handling functions to build robust file‑system logic. Proper conditional checks ensure program correctness and security when using this function.
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.