How to Check if Remote File Exists using PHP

The file_exists() function in PHP, is used to check if a file or directory exists on the server. But the file_exists() function will not usable if you want to check the file existence on the 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 show you how to check if remote file exists using fopen() function in PHP.

// Remote file url
$remoteFile = 'https://www.example.com/files/project.zip';

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

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

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

// Remote file url
$remoteFile = 'https://www.example.com/files/project.zip';

// Initialize cURL
$ch = curl_init($remoteFile);
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 'File exists';
}else{
    echo 'File not found';
}