The file_exists() function in PHP, is used to check if a file or directory exists on the server. But the PHP 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';
}
Your “check if remote file URL exists” doesn’t work as titled.
It returns 200 if the remote directory path is available but the file itself is non existent.
ie.
I have files located here:
example.com/public_files/file1.zip
example.com/public_files/file2.zip
if I search for a file at: example.com/public_files/file99.zip it returns 200 with your function because the directory path itself exists therefore the function does not work as you describe.