Encodera

Thanks for reading!

Donate to the site — we work hard for you.

PHP reference

file_exists

Checks whether a file or folder exists.

Syntax

file_exists(string $filename): bool

Parameters

ParameterTypeDescription
$filenamestringThe path to a file or a folder.

Return value

bool`true` if the path exists.

Examples

An existing and a missing file:

<?php
 
$file = sys_get_temp_dir() . '/ref-exists.txt';
file_put_contents($file, '');
 
var_dump(file_exists($file));
var_dump(file_exists($file . '.missing'));

Output:

bool(true)
bool(false)

Reading with a default value:

<?php
 
$file = sys_get_temp_dir() . '/no-such-file.txt';
 
echo file_exists($file) ? file_get_contents($file) : 'empty';

Output:

empty

Notes

The function returns true for a folder too. To be sure it is a file, use is_file().

See also

Related recipes

In the tutorial

  • Reading and writing files — Working with files in PHP — writing, reading, appending, reading line by line, checking existence and deleting.

Thanks for reading!

Donate to the site — we work hard for you.