file_exists(): Checking file or directory

Check a path before using it

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.

Example 1: Checking for a File in a Subdirectory

<?php
$file_path = 'docs/sample.pdf';
if (file_exists($file_path)) {
    echo "File found: $file_path";
} else {
    echo "File not found.";
}
?>

Example 2: Checking Multiple Files in a Loop

<?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>";
    }
}
?>

Example 3: Using file_exists() for Directories

<?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.

File Deleting all ( or by selection ) files of a directory Directory Functions
PHP


Subscribe to our YouTube Channel here



plus2net.com







Anand

17-08-2010

It helps me 2 much. Thanks




PHP video Tutorials
✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer