The file_exists()
function in PHP is used to check whether a file or directory exists. It returns true
if the file or directory exists, and false
otherwise.
Syntax:
file_exists(string $filename): bool
- $filename: The path to the file or directory.
Example 1: Checking if a file exists
<?php
$file = 'example.txt';
if (file_exists($file)) {
echo "The file '$file' exists.";
} else {
echo "The file '$file' does not exist.";
}
?>
Output:
The file 'example.txt' exists.
Example 2: Checking if a directory exists
<?php
$directory = 'images/';
if (file_exists($directory)) {
echo "The directory '$directory' exists.";
} else {
echo "The directory '$directory' does not exist.";
}
?>
Output:
The directory 'images/' exists.
Example 3: Using with a non-existent file
<?php
$file = 'nonexistent.txt';
if (file_exists($file)) {
echo "The file '$file' exists.";
} else {
echo "The file '$file' does not exist.";
}
?>
Output:
The file 'nonexistent.txt' does not exist.
Important Notes:
file_exists()
can check for both files and directories.- It returns
false
for symlinks pointing to a non-existent target. - Ensure that the script has the correct file permissions to check the file or directory existence.
This function is commonly used for validating the existence of a file before performing further operations like reading or writing to it.
At Online Learner, we're on a mission to ignite a passion for learning and empower individuals to reach their full potential. Founded by a team of dedicated educators and industry experts, our platform is designed to provide accessible and engaging educational resources for learners of all ages and backgrounds.
Terms Disclaimer About Us Contact Us
Copyright 2023-2025 © All rights reserved.