PHP - Check if a file exists or not

By IncludeHelp Last updated : January 10, 2024

Problem statement

Given a file (with or without a directory path), write a PHP program to check if a file exists or not.

Checking if a file exists or not

In PHP, To check if a file exists or not, use the file_exists() function which returns true if the file / directory exists; false, otherwise. You have to provide the file name in file_exists() function, and check the returned value and print appropriate messages.

Note

The file_exists() function can also be used to check the existence of a directory. The method checks whether a file or directory exists or not.

PHP program to check if a file exists or not

Here, we are checking with two files (file1.txt and file2.txt). Where, file1.txt exists on the system and file2.txt does not exist on the system.

<?php
// file name
$file_name1 = "file1.txt";
$file_name2 = "file2.txt";

try {
    // checking whether file (file1.txt) exists or not
    // Note: file1.txt - we have created before the test
    if (file_exists($file_name1)) {
        echo $file_name1 . " exsits." . "<br />";
    } else {
        echo $file_name1 . " does not exsit." . "<br />";
    }

    // checking whether file (file2.txt) exists or not
    // Note: file2.txt - we don't have on the system
    if (file_exists($file_name2)) {
        echo $file_name2 . " exsits." . "<br />";
    } else {
        echo $file_name2 . " does not exsit." . "<br />";
    }
} catch (Exception $e) {
    echo "Execution failed due to this error:" . $e->getMessage();
}
?>

Output

The output of the above program is:

file1.txt exsits.
file2.txt does not exsit.

To understand the above program, you should have the basic knowledge of the following PHP topics:

More PHP File Handling Programs »


Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.