The file_exists Function

The file_exists function checks for the existence of a file or directory at the specified path. The function returns true if the file or directory exists, and false otherwise. A string containing the absolute or relative path to the file is passed to the function parameter.

Syntax

phpfile_exists(string $filename): bool

Example

Let's check if the file 'test.txt' exists in the current directory:

php<?php
  $res = file_exists('test.txt');
  var_dump($res);
?>

Code execution result (if the file exists):

phptrue

Example

Let's check for a non-existent file:

php<?php
  $res = file_exists('nonexistent_file.txt');
  var_dump($res);
?>

Code execution result:

phpfalse

Example

Let's check if a directory exists:

php<?php
  $res = file_exists('images/');
  var_dump($res);
?>

Code execution result (if the directory exists):

phptrue

See Also

  • the is_dir function,
    which checks for a folder
  • the is_file function,
    which checks for a file
  • the is_readable function,
    which checks readability
  • the is_writable function,
    which checks writability