Master PHP’s file_exists(): How to Check Files & Directories Efficiently
This article explains how to use PHP's built‑in file_exists() function to reliably check the existence of local and remote files or directories, outlines its syntax, provides practical code examples, and highlights important limitations and best‑practice considerations.
In PHP programming we often need to determine whether a file exists, which can be done using the built‑in file_exists() function. This article introduces the usage of file_exists() and some important considerations.
1. Overview of file_exists()
The file_exists() function checks if a file or directory exists, returning true if it does and false otherwise. It accepts a single argument that can be a local or remote path.
2. Syntax
file_exists(file)Parameter: file – the filename or directory name; remote files must start with http:// or ftp://.
Return value: true if the file or directory exists, false otherwise.
3. Example Code
The following code demonstrates how to use file_exists():
// Check local file
$file = './test.txt';
if (file_exists($file)) {
echo '文件存在';
} else {
echo '文件不存在';
}
// Check remote file
$file = 'http://www.example.com/test.txt';
if (file_exists($file)) {
echo '文件存在';
} else {
echo '文件不存在';
}
// Check directory
$dir = './example';
if (file_exists($dir)) {
echo '目录存在';
} else {
echo '目录不存在';
}4. Precautions
The file_exists() function can only determine the existence of a file or directory; it cannot tell whether the path is a file or a directory. It works for local and remote files but does not indicate readability or writability. When using file_exists() together with other file operations, be aware of potential file‑locking issues.
In summary, file_exists() is frequently used in PHP to conveniently check the presence of files and directories, reducing code complexity and improving development efficiency.
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.
