file_exists
Checks whether a file or folder exists.
Syntax
file_exists(string $filename): boolParameters
| Parameter | Type | Description |
|---|---|---|
| $filename | string | The 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:
emptyNotes
The function returns true for a folder too. To be sure it is a file, use is_file().
See also
- is_dir — Checks whether a path is a folder.
- file_get_contents — Reads a whole file into a string.
- unlink — Deletes a file.
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.