Open In App

PHP file_exists( ) Function

Last Updated : 15 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

The file_exists() function in PHP checks whether a file or directory exists on the server. It returns a boolean value:

  • true: If the file or directory exists.
  • false: If the file or directory does not exist or the path is incorrect.

Syntax:

file_exists($path)

In this syntax:

  • The file_exists() function in PHP accepts only one parameter, $path. It specifies the path of the file or directory you want to check.

Return Value:

  • true: If the file or directory exists.
  • false: If the file or directory does not exist, or the path is incorrect.

Example Usage of file_exists()

Let's take a simple example that checks if a file exists using file_exists().

PHP
<?php
$file = "example.txt";

if (file_exists($file)) {
    echo "The file '$file' exists.";
} else {
    echo "The file '$file' does not exist.";
}
?>

In this example:

  • we specify the file name as "example.txt".
  • If the file exists in the current directory, the message The file 'example.txt' exists. will be displayed.
  • If the file doesn't exist, the message The file 'example.txt' does not exist. will be shown.

Checking a Directory

The file_exists() function also works with directories. Here's an example that checks if a directory exists:

PHP
<?php
$directory = "uploads/";

if (file_exists($directory)) {
    echo "The directory '$directory' exists.";
} else {
    echo "The directory '$directory' does not exist.";
}
?>

In this example:

  • In this example, we check if a directory named "uploads/" exists.
  • If the directory exists, the browser will display: The directory 'uploads/' exists.

Conclusion

The file_exists() function in PHP is a powerful tool for verifying the existence of files or directories before performing operations on them. It helps prevent errors by ensuring that files are available for reading, writing, or manipulation, and can be used in conjunction with other functions like is_file() and is_dir() to get more detailed information about the file system. Understanding how to properly use file_exists() will make your file-handling scripts more robust and error-free.


Next Article
Practice Tags :

Similar Reads