How to Check if File Exists on Remote Server using PHP


Check if File Exists on Remote Server

Demo Download

In this tutorial, we will learn about how to check if file exists on remote server using PHP with easy and simple methods.

Although, PHP provides a build in file_exists() function to check if file exist on server. However, this function is not able to check remote file on remote server.

So how can one check if a file exists from a URL using PHP without file_exists() function.

PHP provides alternatives functions and we will use other methods that will check if remote file exist on remote server using PHP.

There are two ways to check file on remote server in PHP which are listed below:

  1. fopen() Function
  2. cURL Method

1. fopen() Function

The best and the easiest way to check if file exist on remote server is using a fopen() function in PHP.

You can use the following code to check if remote file exist using PHP.

// Remote file URL
$remote_file_url = 'https://www.example.com/pdf/filename.pdf';

// Open file using fopen() function
$file_exist = @fopen($remote_file_url, 'r');

// Check if file exists on remote server
if($file_exist){
    echo 'Remote file exists.';
}else{
    echo 'Remote file is not found!';
}

Readers Also Read: How to Attach Remote File to Email using PHPMailer

2. cURL Method

Alternatively, you can also use cURL Method to check if remote file exist on remote server using PHP.

Use the following code snippet to check if file exist from a URL on remote server using PHP.

// Remote file URL
$remote_file_url = 'https://www.example.com/pdf/filename.pdf';

// Initialize a cURL session
$curl = curl_init($remote_file_url);

// Set CURLOPT_NOBODY true to exclude body from output
curl_setopt($curl, CURLOPT_NOBODY, true);

//Execute the current cURL session
curl_exec($curl);

// Get an HTTP response code
$response_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);

// Close cURL session
curl_close($curl);

// Check if file exists on remote server
if($response_code == 200){
    echo 'Remote file exists.';
}else{
    echo 'Remote file is not found!';
}

Conclusion

By now we hope that you have learnt how to check if remote file exists on remote server using PHP by using any of the above available methods.

If you found this tutorial helpful, share it with your friends and developers group.

I spent several hours to create this tutorial, if you want to say thanks so like my page on Facebook, Twitter and share it.

Demo Download

Readers Also Read: How to Send Email in PHP Using PHPMailer Library

Facebook Official Page: All PHP Tricks

Twitter Official Page: All PHP Tricks

Article By
Javed Ur Rehman is a passionate blogger and web developer, he loves to share web development tutorials and blogging tips. He usually writes about HTML, CSS, JavaScript, Jquery, Ajax, PHP and MySQL.

Leave a Reply

Your email address will not be published. Required fields are marked *