Using PHP file_exists() to Check File and Directory Existence
This article explains the PHP file_exists() function, covering its syntax, return values, practical examples for checking local and remote files as well as directories, and important limitations to consider when using it in backend development.
In PHP programming, we often need to determine whether a file or directory exists, which can be done using the built‑in file_exists() function. This article introduces the usage of file_exists() and several important considerations.
1. Overview of file_exists()
The file_exists() function checks whether a file or directory exists; it returns true if it exists and false otherwise. It accepts a single argument that can be a local path, a directory name, or a remote URL (starting with http:// or ftp:// ).
2. Function Syntax
file_exists(file)Parameter: file – the filename or directory name; for remote files it must start with http:// or ftp:// .
Return value: true if the file or directory exists, otherwise false .
3. Example Code
The following code demonstrates how to use file_exists() for local files, remote files, and directories.
// Check if a local file exists
$file = './test.txt';
if (file_exists($file)) {
echo '文件存在';
} else {
echo '文件不存在';
}
// Check if a remote file exists
$file = 'http://www.example.com/test.txt';
if (file_exists($file)) {
echo '文件存在';
} else {
echo '文件不存在';
}
// Check if a directory exists
$dir = './example';
if (file_exists($dir)) {
echo '目录存在';
} else {
echo '目录不存在';
}4. Important Notes
The file_exists() function can only determine whether a path exists; it cannot tell whether the path is a file or a directory. It works for both local and remote resources, but it does not check readability or writability of local files. When using file_exists() together with other file‑handling functions, be aware of potential file‑locking issues.
In summary, the file_exists() function is frequently used in PHP development to conveniently verify the existence of files and directories, reducing code complexity and improving development efficiency.
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.