How to Check If a File Exists In PHP?

Problem:

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

Solution:

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

Example:

<?php
    $file = "./sidebar.php";
    if (file_exists($file)){
        echo "The file $file exists.";
    }else{
        echo "The file $file does not exist.";
    }
    clearstatcache();
?>

Output:

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)

Usages:

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

Syntax:

file_exists(filename)

Parameters:

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

<?php
     $folder = "./images”;
     if (file_exists($folder)){
         echo "The folder $folder exists.";
     }else{
         echo "The folder $folder does not exist.";
     }
 clearstatcache();
 ?>

Output:
The folder ./images exists.