How to Check If a File Exists In PHP?


You’re going to add a file in your php code or you’re adding photos in the photo gallery. Before adding any file, you want to make sure that the file exists.

For example, the following is the file/folder structure of your current directory. You’re writing code in the index.php file and now you want to make sure that the file sidebar.php exists before adding this.

php file_exists() function


Use file_exists() function to check the existence of a file.


    $file = "./sidebar.php";
    if (file_exists($file)){
        echo "The file $file exists.";
        echo "The file $file does not exist.";


The file ./sidebar.php exists.

How it works:

Line 2 Indicates the file sidebar.php which we like to include. The ./ indicates the location of the file is in the current directory.
Line 3 The function file_exists() checks and finds the file sidebar.php in the current exists and return true.
Line 4 As the if statement returns true in line 3, it prints this line.
Line 8 The function clearstatcache() clears the cache. It is required as php caches the return information of the function file_exists() to provide faster performance. Without it, you may get unexpected output.

To indicate the location of the file in the current directory we used ./ (“./sidebar.php”). You can discard that too (like “sidebar.php”). But, don’t discard the dot only (“/sidebar.php”) which indicates the absolute path of the file and the file is not located there.

file_exists() function at a glance

(PHP4, PHP5)


file_exists() function checks whether a file or folder exists.




Parameter What it does
filename Required Specify the file/folder to be searched with its path

Example 1: How to check if a folder exists?

We want to check whether the folder “images” exists in the current directory (see the image below).

php file_exists() function

     $folder = "./images”;
     if (file_exists($folder)){
         echo "The folder $folder exists.";
         echo "The folder $folder does not exist.";

The folder ./images exists.