PHP file_exists() | Check if File or Directory Exists

The PHP file_exists() function is used when we need to check whether a file or a directory exists or not. For example:

<?php
   $x = file_exists("codescracker.txt");
   if($x)
      echo "<p>The specified file is available.</p>";
   else
      echo "<p>The specified file is not available.</p>";
?>

The output of above PHP example on file_exists() function is:

php file_exists function

Since the file codescracker.txt is available in the current directory, therefore the above example produces the output that you have seen.

PHP file_exists() Syntax

The syntax of file_exists() function in PHP, is:

file_exists(path)

PHP file_exists() Example

<?php
   $file = "codescracker.txt";
   if(file_exists($file))
      echo "<p>The file, <b>$file</b> exists.</p>";
   else
      echo "<p>The file, <b>$file</b> does not exists.</p>";
   
   $path = "C:\Users\DEV\codescracker.com";
   if(file_exists($path))
      echo "<p>The path, <b>$path</b> exists.</p>";
   else
      echo "<p>The path, <b>$path</b> does not exists.</p>";
?>

In above program, both the file and the path exists, therefore the output produced by above PHP example should be:

php file exists example

PHP Online Test


« Previous Tutorial Next Tutorial »

Like/Share Us on Facebook 😋