How to check whether a file exists
Short answer
is_file() returns true only if the path exists and is a file:
<?php
$file = sys_get_temp_dir() . '/recipe-exists.txt';
file_put_contents($file, 'x');
var_dump(is_file($file));
var_dump(is_file($file . '.missing'));Output:
bool(true)
bool(false)Why not file_exists()
file_exists() answers true for a folder as well:
<?php
$dir = sys_get_temp_dir();
var_dump(file_exists($dir), is_file($dir), is_dir($dir));Output:
bool(true)
bool(false)
bool(true)Can it be read
A file may exist yet be inaccessible. Check is_readable() before reading:
<?php
$file = sys_get_temp_dir() . '/recipe-exists.txt';
file_put_contents($file, 'data');
echo is_readable($file) ? file_get_contents($file) : 'cannot read';Output:
dataFunctions used in this recipe
- is_file — Checks that a path exists and is a file rather than a folder.
- file_exists — Checks whether a file or folder exists.
- is_readable — Checks that a file exists and can be read.