Using PHP file_exists() to Check File and Directory Existence
This article explains how the PHP file_exists() function works, its syntax, return values, usage examples for local and remote files as well as directories, and important considerations when employing it in backend development.
In PHP programming we often need to determine whether a file or directory exists, which can be done with the built‑in file_exists() function. This article introduces the usage of file_exists() and several important notes.
file_exists() Function Overview
The file_exists() function checks if a file or directory exists; it returns true when the target is found and false otherwise. It accepts a single argument that can be a filename or a directory name, and it works with both local and remote resources.
Function Syntax
<code>file_exists(file)</code>Parameter description:
file – the name of a file or directory. For remote resources the path must start with http:// or ftp:// .
Return value: true if the file or directory exists, false otherwise.
Example Code
The following code demonstrates how to use file_exists() :
<code>// Check if a local file exists
$file = './test.txt';
if (file_exists($file)) {
echo 'File exists';
} else {
echo 'File does not exist';
}
// Check if a remote file exists
$file = 'http://www.example.com/test.txt';
if (file_exists($file)) {
echo 'File exists';
} else {
echo 'File does not exist';
}
// Check if a directory exists
$dir = './example';
if (file_exists($dir)) {
echo 'Directory exists';
} else {
echo 'Directory does not exist';
}
</code>Important Considerations
The file_exists() function can only determine whether a path exists; it cannot tell whether the path is a file or a directory.
It does not provide information about read or write permissions for local files.
When using file_exists() together with other file‑handling functions, be aware of potential file‑locking issues.
The file_exists() function is frequently used in PHP backend development because it simplifies existence checks, reduces code complexity, and improves overall coding 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.