Check File exists or not in PHP

While working with file download functionality with the database, we commonly face an error that says file not found. So if we add functionality to check file exists or not before the actual searching file then we can provide a better user experience.

PHP provides many built-in functions to handle file operations easily. Some of those functions are related to our concept. In this tutorial, we will use those functions and check file exists or not in a server using PHP.

The functions like file_exists(), is_file(), is_readable(), and is_writable() are used to check file status in PHP. Each function has its own individual use. i.e. the file_exists() function will check file exists or not while the is_file() function will check given file is a file or not.

Check if a File Exists using file_exists() Function

To check file exists or not, we can use the file_exists() function. It accepts one parameter and returns a boolean based on operations. If a given file exists then it will return true otherwise false.

Following is a simple example of using the file_exists() function to check file exists or not:

<?php
    $filename = 'file.txt';

    if (file_exists($filename)) {
        $message = "File exists";
    } else {
        $message = "File does not exist";
    }
    echo $message;
?>

In the above example, we have a statically defined file name and use the file_exists function. It prints messages based on file status. In some cases, the file name can be a directory too.

Check if file Exists using is_file() Function

If we want to check specifically for files, not for directories then we can use the is_file() function. The is_file() function accepts a file name and returns true or false based on its existence.

Let’s convert the previous example with this method:

<?php
    $filename = 'file.txt';

    if (is_file($filename)) {
        $message = "File exists";
    } else {
        $message = "File does not exist";
    }
    echo $message;
?>

The is_file() function will ignore the directory and check specially for the file.

Conclusion

In this article, we have taken some examples where we checked whether a file exists or not using file functions in PHP. Two more functions can be used for this purpose but those functions are used to check permission. We can use is_readable() and is_writable() functions to check file exists or not.