Check file exists or not using PHP

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

PHP provides many in-built function to handle file operation easily. Some of those functions are related to our concept. In this tutorial, we will use those function and check file exists or not in 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 it's individual use. i.e the file_exists() function will check file exists or not while is_file() function will check given file is actually file or not.

Check if a File Exists using file_exists() Function

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

Following is simple example to use 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 above example, we have statically defined file name and used file_exists function. It prints message based on file status. In some case file name can be directory too.

Check if File Exists using is_file() Function

If we want to check specifically for file not for directory then we can use is_file() function. The is_file() function accepts a file name and returns true or false based on it's existence.

Let's convert 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 directory and check specially for file.

Conclusion

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


Share your thoughts

Ask anything about this examples