Skip to content
Tutorials Center
My learning

Topics

PHP Reference ยท Files and I/O

PHP file_exists() and is_file() functions

Reference for PHP file_exists(), is_file(), is_readable() and is_writable(): check paths before using them, differences between files and directories, and race conditions.

file_exists() returns true when a path exists, whether it is a file or a directory. is_file() is stricter: only a regular file counts. is_readable() and is_writable() additionally check permissions for the current process. All of them return a plain boolean and never raise errors; a path they cannot check is simply false.

Use them to choose a code path (create a default file, skip a missing cache), not as a guarantee: the file can change between the check and the next call.

PHP
if (is_file($path) && is_readable($path)) {
    $text = file_get_contents($path);
}

Try it

PHP File, directory or nothing

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

PHP Create a file only if missing

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Syntax

PHP
file_exists(string $filename): bool
is_file(string $filename): bool
is_readable(string $filename): bool
is_writable(string $filename): bool
Name Description
$filename Path to check, relative to the current directory or absolute.

Return value: true or false. No exceptions or warnings are produced for missing paths.

Usage notes

  • file_exists() is true for directories. Use is_file() when you need a file and is_dir() for a directory.
  • Symbolic links are followed. A broken link reports false from all of these.
  • Results are cached. PHP caches stat results for the request; call clearstatcache() if the file is created or deleted by other code and you check it again.
  • Race conditions. Between the check and the use, another process can create or delete the file. For "create only if absent" use fopen($path, "x"), which is atomic; for reading, just try and check the result.
  • Empty string is always false.
  • Permissions are checked for the user that runs PHP, which is often a different user than yours.
  • is_writable() for a new file: test the directory, not the file that does not yet exist.
  • Remote URLs: file_exists() works with some wrappers (such as file://) but not http://.
  • Security: never pass raw user input as a path; see realpath() checks and whitelists.