php

How to check if file exists on remote server PHP

In this tutorial, we are going to see how to check if file exists on remote server in PHP. The function file_exists() in PHP allows you to check if a file or a directory exists on the server. But the function file_exists() will not be usable if you want to check the existence of the file on a remote server. The fopen() function is the easiest solution to check if a file URL exists on a remote server using PHP.

The following code snippet shows you how to check if a remote file exists using fopen() function in PHP.
 

Method 1: How to check if file exists on remote server using fopen() in PHP
<?php
	// Remote file url
	$rFile = 'https://www.example.com/files/exemple.pdf';

	// Open the file
	$check = @fopen($rFile, 'r');

	// Check if the file exists
	if(!$check){
		echo 'File does not exist';
	}else{
		echo 'File exists';
	}
?>

Output:

File does not exist

 

 

Method 2: How to check if file exists on remote server using cURL in PHP

You can also use cURL to check if a URL exists on the remote server. The following code snippet shows you how to check if a remote file url exists using cURL in PHP.

<?php
	// Remote file url
	$rFile = 'https://www.example.com/files/exemple.pdf';

	$ch = curl_init($rFile);
	curl_setopt($ch, CURLOPT_NOBODY, true);
	curl_exec($ch);
	$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
	curl_close($ch);

	// Check the response code
	if($code == 200){
		echo 'File does not exist';
	}else{
		echo 'File exists';
	}
?>

Output:

File does not exist
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

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