file_exists() checks whether a file or directory exists. When your next step specifically needs a file or directory, is_file() or is_dir() makes the intention clearer.
$path = __DIR__ . '/data.txt';
if (file_exists($path)) {
echo 'The path exists.';
}
if (is_file($path)) {
echo ' It is a file.';
}This example shows the recommended starting pattern. Continue below for variations, explanation and the original practical examples.
$add="images/119.jpg";
if(file_exists($add)){
echo "Yes file is there ";
}else{
echo "Sorry no file at $add ";
}
In our script before executing a program we need to check if file exists or not. This file check method by using file_exists function check the presence of file from relative path we specify and then returns TRUE of False based on the presence of the file.
<?php
$file_path = 'docs/sample.pdf';
if (file_exists($file_path)) {
echo "File found: $file_path";
} else {
echo "File not found.";
}
?>
<?php
$files = ['image1.jpg', 'image2.jpg', 'image3.jpg'];
foreach ($files as $file) {
if (file_exists($file)) {
echo "$file exists.<br>";
} else {
echo "$file does not exist.<br>";
}
}
?>
<?php
$dir = 'uploads';
if (file_exists($dir) && is_dir($dir)) {
echo "Directory exists.";
} else {
echo "Directory not found.";
}
?>
These examples show various ways to use `file_exists()` to check for files and directories.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.
| Anand | 17-08-2010 |
| It helps me 2 much. Thanks | |