Tuesday, 14 August 2018

How to Check If a File Exists In PHP?

Problem:

You’re going to add a file in your php code or you’re adding photos in the photo gallery. Before adding any file, you want to make sure that the file exists.
For example, the following is the file/folder structure of your current directory. You’re writing code in the index.php file and now you want to make sure that the file sidebar.php exists before adding this.
php file_exists() function

Solution:

Use file_exists() function to check the existence of a file.
Example:
1
2
3
4
5
6
7
8
9
<?php
    $file = "./sidebar.php";
    if (file_exists($file)){
        echo "The file $file exists.";
    }else{
        echo "The file $file does not exist.";
    }
    clearstatcache();
?>
Output:
The file ./sidebar.php exists.

How it works:

Line 2Indicates the file sidebar.php which we like to include. The ./ indicates the location of the file is in the current directory.
Line 3The function file_exists() checks and finds the file sidebar.php in the current exists and return true.
Line 4As the if statement returns true in line 3, it prints this line.
Line 8The function clearstatcache() clears the cache. It is required as php caches the return information of the function file_exists() to provide faster performance. Without it, you may get unexpected output.
To indicate the location of the file in the current directory we used ./ (“./sidebar.php”). You can discard that too (like “sidebar.php”). But, don’t discard the dot only (“/sidebar.php”) which indicates the absolute path of the file and the file is not located there.

file_exists() function at a glance

(PHP4, PHP5)
Usages:
file_exists() function checks whether a file or folder exists.
Syntax:
file_exists(filename)
Parameters:
ParameterWhat it does
filenameRequiredSpecify the file/folder to be searched with its path

Example 1: How to check if a folder exists?

We want to check whether the folder “images” exists in the current directory (see the image below).
php file_exists() function
1
2
3
4
5
6
7
8
9
<?php
     $folder = "./images”;
     if (file_exists($folder)){
         echo "The folder $folder exists.";
     }else{
         echo "The folder $folder does not exist.";
     }
 clearstatcache();
 ?>
Output: 
The folder ./images exists.

0 comments:

Post a Comment