How to check if file or directory exists in PHP

How to check if file exists in PHP

Sometimes we need to check if file exists on the server or not before performing some task. PHP provides file_exists() function to check if file or directory exists.

file_exists() returns TRUE if the file or directory exists , otherwise it return FALSE.

To check if a file exists, you use the file_exist() function. This function returns TRUE if the file exists, otherwise, it returns FALSE.

Let’s see in the below example, we check with the file name in function if the file exists or not. You can also mention a directory or folder path to check if that folder or directory exists or not.

<?php
$filename = 'test.txt';
if(file_exists($filename)){
 echo "file exists";
}else{
 echo "file not found";
}
?>

Spread the love