PHP Check If File Exists in a Folder

PHP to verify if a File exists in Directory

In PHP, to check if a file exists in a folder path – use the function: ‘file_exists‘.

Syntax: file_exists (‘filepath’)

This fucntion takes the input as file along with complete path to this function.

If the file is present, then this function will return True, otherwise False.

PHP Code to check if File is Present

Here is a sample code example:

$pathtofile = '/folder1/subfolder1/filename.ext'; 

'Clear cache to remove result from previous run
clearstatcache();

//Check if file is present & Returns True or False 
echo file_exists($pathtofile); 

//How to use this file_exists in If condition
clearstatcache();
if (file_exists($pathtofile)) { 
    echo "File found in directory path";} 
else { 
    echo "File not found in the path";
}

The return code can be printed or assigned to a Boolean variable & used inside your php code.

Important Note: There is chance that even if the file is moved to a different place, the function still returns a previous return code. It is because the function uses cache.

It is always a good practice to use ‘clearstatcache()’ prior to using the file management functions. That way, we will always get the latest result.

External Reference: Here is another link to this PHP file_exists function.