how to check if a file exists in php?

Today, We want to share with you php file exists.In this post we will show you The file_exists() function checks whether a file or directory exist., hear for how to check if a file exist using file_exists(), is_readable() and is_writable() functions. we will give you demo and example for implement.In this post, we will learn about How to increment the filename if file already exist in PHP? with an example.

PHP file_exists() Function

To check if a file exist, you use the the file_exist() function.
PHP file exists only


The script checks to see if the testdemo.txt file exist in the same folder with the script file.
PHP file exist and readable


PHP file exists and writable


The script checks whether the ./testdemo.txt file exists and is writable.
PHP check if file exists in folder

To check if a file exists in a folder using PHP, you can use the file_exists() function. This function takes the path of the file as its argument and returns true if the file exists, and false otherwise.

Here's an example:



In this example, we first define the name of the file ($filename) and the path to the folder where the file should be located ($folder). We then use the file_exists() function to check if the file exists in the specified folder.

Note that the file_exists() function can also be used to check if a file exists on a remote server, by specifying a URL instead of a file path. However, this may be slower and less reliable than checking for local files.

How to Check if Remote File Exists using PHP?

It's a check if a file or directory/folder exist on the live web server. But the file_exists() function will not usable if you want to check the file existence on the remote server.

The bellow source code show you how to check if remote file exist using fopen() function in PHP.

// Remote file url
$live_fl = 'https://www.your_domain_name.com/files/application.zip';

// Open file
$handle = @fopen($live_fl, 'r');

// Check if file exist
if(!$handle){
    echo 'Your XYZ File not found';
}else{
    echo 'Your XYZ File exist';
}

how to check if remote file URL exist using cURL in PHP?

// Remote file url
$live_fl = 'https://www.your_domain_name.com/files/application.zip';

// Initialize cURL
$ch = curl_init($live_fl);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_exec($ch);
$responseCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

// Check the response code
if($responseCode == 200){
    echo 'Your XYZ File exist';
}else{
    echo 'Your XYZ File not found';
}

I hope you get an idea about Checking whether a file exist: file_exists().
I would like to have feedback on my infinityknow.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.

Leave a Comment