Using PHP file_exists() to Check File and Directory Existence

This article explains the PHP 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 for reliable file system operations.

php Courses
php Courses
php Courses
Using PHP file_exists() to Check File and Directory Existence

In PHP programming, the file_exists() function is used to determine whether a specified file or directory exists, enabling appropriate handling based on the result.

Syntax: bool file_exists ( string $filename ) Parameter: $filename: The path of the file or directory to be checked.

Return value: Returns true if the file or directory exists, otherwise false.

Example: The following code demonstrates how to use file_exists() to check a file and a directory.

<?php<br/>// Check if a file exists<br/>$file = 'example.txt';<br/>if (file_exists($file)) {<br/>    echo "File exists.";<br/>} else {<br/>    echo "File does not exist.";<br/>}<br/><br/>// Check if a directory exists<br/>$dir = 'example_dir';<br/>if (file_exists($dir) && is_dir($dir)) {<br/>    echo "Directory exists.";<br/>} else {<br/>    echo "Directory does not exist.";<br/>}<br/>?>

The script first defines a file path variable $file and uses file_exists() to verify its existence, outputting a corresponding message. 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 file_exists() function can check both local and remote files by providing a URL as the argument.

The function does not differentiate between files and directories; it returns true for either.

It only reports existence and does not impose access restrictions.

It is advisable to use is_readable() or is_writable() before accessing a file to avoid permission‑related errors.

Conclusion: file_exists() is a fundamental PHP function for verifying the presence of files or directories, and when combined with proper conditional checks, it helps ensure correct and secure file handling in backend applications.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Backendphp-functionsfile_existsfile check
php Courses
Written by

php Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.