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

<?php
 
$your_fl_name = './testdemo.txt';
 
if(file_exists($your_fl_name)){
 echo sprintf('file %s exist',$your_fl_name);
}else{
 echo sprintf('file %s does not exist',$your_fl_name);
}

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 
$your_fl_name = './testdemo.txt';
 
if(is_readable($your_fl_name)){
 echo sprintf('file %s exist and readable',$your_fl_name);
}else{
 echo sprintf('file %s does not exist or is not readable',$your_fl_name);
}

PHP file exists and writable

<?php
$your_fl_name = './testdemo.txt';
 
if(is_writable($your_fl_name)){
 echo sprintf('file %s exist and writable',$your_fl_name);
}else{
 echo sprintf('file %s does not exist or is not writable',$your_fl_name);
}

The script checks whether the ./testdemo.txt file exists and is writable.

Read Also:  Angular 9/8 Select Dropdown | Get Selected DropDown Value on Change Event

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.