Course Content
State Management
0/1
Regular Expressions?
0/1
About Lesson

Check if a File Exists?

In PHP, the file_exists() function is used to determine whether a specified file or directory exists. It returns true if the file or directory exists and false otherwise. Here’s how to use file_exists():

Syntax:

bool file_exists ( string $filename )

$filename: Specifies the path to the file or directory to check.  Example:

PHP
<?php
$filename = 'example.txt';

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

Important Points:

  • file_exists() can be used to check both files and directories.
  • It accepts a string parameter representing the file or directory path.
  • You can use absolute or relative paths.
  • Ensure that the file path is correctly specified and that the PHP script has sufficient permissions to access the file or directory.

Example Use Cases:

  • Before attempting to read from or write to a file, it’s a good practice to check if the file exists to avoid errors.
  • You can use file_exists() to verify the existence of uploaded files before processing them in web applications.
  • It’s commonly used in file management scripts to handle files dynamically.

In summary, file_exists() is a handy function for checking the existence of files and directories in PHP applications. It helps ensure that your code operates on valid file paths and directories, contributing to the reliability and robustness of your PHP scripts.