Checking File or Directory Existence in PHP using the file_exists() Function

29-01-2023
PHP

Learn how to check if a file or directory exists in PHP using the file_exists() function. This is a simple and easy way to verify if a file or folder is present in a certain location. It’s useful for many file management tasks and can be easily implemented in your PHP code. Get started with examples and sample code to help you use file_exists() in your project.

The file_exists() function in PHP is used to check if a file or directory exists. It returns TRUE if the file or directory specified in the path exists, and FALSE otherwise.

Here is an example of using the file_exists() function to check if a file called “example.pdf” exists in the current directory:


<?php
if (file_exists("simple.pdf")) {
echo "The file exists";
} else {
echo "The file does not exist";
}
?>

In this example, the function is used to check if the file “example.pdf” exists in the current directory. If it does, the script will output “The file exists”; if it doesn’t, the script will output “The file does not exist”.

You can also use file_exists() to check directory exist or not in the same way.


<?php 
if (file_exists("/path/to/file_directory")) { 
   echo "The directory exists"; 
} else { 
   echo "The directory does not exist"; 
} 
?>