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 the above PHP example on the file_exists() function is:

php file_exists function

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

PHP file_exists() Syntax

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

file_exists(path)

PHP file_exists() Example

Consider the following PHP code as an example demonstrating the "file_exists()" function:

<?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 the above program, both the file and the path exist; therefore, the output produced by the above PHP example should be:

php file exists example

In the above example, "codescracker.txt" is assigned to $file. Then file_exists() checks if this file exists. It outputs the file name and message if the file exists. It displays the file name and a message if the file does not exist.

Next, the code sets $path to "C:\Users\DEV\codescracker.com". Then file_exists() checks if this path exists. It outputs the path name and a message if the path exists. It displays the path name and a message if the path does not exist.

When checking directory paths, use the server's file system syntax. This path uses the backslash character (\) to separate directories.

Advantages of the file_exists() function in PHP

Disadvantages of the file_exists() function in PHP

PHP Online Test


« Previous Tutorial Next Tutorial »


Liked this post? Share it!