PHP and MySQL (56 Blogs) Become a Certified Professional

How to Implement file_exists function in PHP?

Published on Sep 18,2019 1000 Views

A file is a resource for storing data and PHP has a rich collection of built-in functions that simplifies your work with files. The file_exists() function in PHP is an inbuilt function which is used to check whether a file or directory exists or not. In this article, we will see how to implement file_exists in PHP in the following sequence:


file_exists() in PHP

It is a built-in function that can be used to check whether a file exists or does not exist. When we want to know if a file exists or not before processing, it comes in handy. You can also use this function when creating a new file and you want to ensure that the file does not already exist on the server.

PHP- file_exists in php - edureka





It accepts only one parameter. i.e path which specifies the directory or path of the file whichever we want to check. It would return true on successful execution and returns false on failure execution.

If the path specifies point to non-existent files, file_exists() returns false. Some of the file system functions may give unexpected results for files that are larger than 2GB as PHP integer type is signed and many platforms use 32bit integers.



Usually, the result of file_exists() is cached. In order to clear the cache we use clearstatcache(), You need to avoid caching to get correct results, If a file is to be checked several times in a script. We clearstatcache() function in order to perform this.


clearstatcache(clear_realpath_cache, filename)


Both the parameters are optional where Clear_realpath_cache indicates whether to clear the realpath cache or not. By default, it is FALSE, which indicates not to clear realpath cache and filename specifies name of the file, and clears the realpath and cache for that file only.


Below example demonstrates the working of file_exists in PHP:


if (file_exists('create_file.txt'))
    echo 'file found!';
    echo 'create_file.txt does not exist';


As the file does not exist, which means the path specified point to non-existent file so it returns false and executes the else part.

With this, we come to an end of this article. I hope you have learned about the inbuilt function file_exists() and clearstatcache() in PHP.

If you found this PHP blog relevant, check out the PHP Certification Training by Edureka, a trusted online learning company with a network of more than 250,000 satisfied learners spread across the globe.

Got a question for us? Please mention it in the comments section of ”file_exists in PHP” and I will get back to you.


Join the discussion

Browse Categories

webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP

Subscribe to our Newsletter, and get personalized recommendations.

image not found!
image not found!

How to Implement file_exists function in PHP?