Backend Development 4 min read

Using PHP file_exists() to Check File and Directory Existence

This article explains the PHP file_exists() function, its syntax, parameters, return values, provides example code for checking both files and directories, and lists important usage notes and best practices for reliable file handling.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Using PHP file_exists() to Check File and Directory Existence

In PHP programming, checking whether a file or directory exists is a common task, and the file_exists() function is used for this purpose.

Syntax:

bool file_exists ( string $filename )

Parameter:

$filename : the path of the file or directory to check.

Return value: Returns true if the file or directory exists, otherwise false .

Example: The following example demonstrates how to use file_exists() to check a file and a directory.

<?php
// Check if a file exists
$file = 'example.txt';
if (file_exists($file)) {
echo "File exists.";
} else {
echo "File does not exist.";
}
// Check if a directory exists
$dir = 'example_dir';
if (file_exists($dir) && is_dir($dir)) {
echo "Directory exists.";
} else {
echo "Directory does not exist.";
}
?>

The script first defines a file path variable $file and uses file_exists() to determine its existence, outputting an appropriate message. It then defines a directory path variable $dir and checks both existence and that it is a directory using file_exists() together with is_dir() .

Notes:

The function can also check remote files by providing a URL.

It does not differentiate between files and directories; a directory will also return true .

It only reports existence and does not consider accessibility permissions.

It is advisable to use is_readable() or is_writable() before accessing the file to avoid permission errors.

Conclusion: The file_exists() function is essential for verifying the presence of files or directories in PHP, enabling developers to write safe conditional logic for file handling.

BackendPHPphp-functionsfile_existsfile-check
php中文网 Courses
Written by

php中文网 Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.