How to Check If a File Exists in PHP

09/05/2021

Contents

In this article, you will learn how to check if a file exists in PHP.

PHP file_exists() Function

To check if a file exists in PHP, you can use the file_exists() function:

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

Where $file is the path to the file you want to check.

The file_exists() function in PHP is a simple way to check if a file exists on the server. The function returns TRUE if the file exists, and FALSE if it doesn’t.

Here’s an example of how to use file_exists() to check if a file exists before attempting to read its contents:

<?php
  $file = 'example.txt';

  if (file_exists($file)) {
    $content = file_get_contents($file);
    echo "File contents: $content";
  } else {
    echo "File does not exist.";
  }
?>

In this example, if the file exists, its contents will be read and displayed. If the file does not exist, an error message will be displayed.

Note: the file_exists() function is case-sensitive, so make sure to use the correct case for the file name.