Using PHP file_exists() to Check File and Directory Existence
This article explains PHP's file_exists() function, detailing its syntax, parameters, return values, usage examples for checking both files and directories, and important considerations such as remote checks and permission handling in web applications.
In PHP programming, the file_exists() function is used to determine whether a specified file or directory exists.
Syntax: bool file_exists ( string $filename )
Parameter:
$filename : the path of the file or directory to check.
Return value: Returns true if the file or directory exists, otherwise false .
Example: The following code demonstrates checking a file and a directory.
The example first defines a file path variable $file and uses file_exists() to verify its existence, outputting a message accordingly. It then defines a directory path variable $dir and checks both existence and that it is a directory using file_exists() together with is_dir() .
Notes:
The function can check local files/directories as well as remote URLs.
It does not differentiate between files and directories; a directory will also return true .
It only reports existence and does not impose access restrictions.
It is advisable to use is_readable() or is_writable() before accessing the file to avoid permission errors.
Summary: file_exists() is an essential PHP function for verifying the presence of files or directories, returning a boolean result that can be combined with other file‑handling functions to build robust file‑system logic.
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.