Clue Mediator

How to check if a file exists from a URL in PHP

📅November 11, 2020
🗁PHP

Today we’ll explain to you how to check if a file exists from a URL in PHP. Using php built-in file_exists() function, we can check whether a file or directory exists on the server or not but will not use it to check if a file exists on a remote server or not.

Sometimes we need to check the given image URL or another file URL that exists or not so this will help you.

Different ways to check file exists on remote server or not

  1. Using fopen() function
  2. Using get_headers() function
  3. Using cURL function

1. Using fopen() function

Here, we will create a custom function to check if a file exists on a remote server or not using fopen() function in PHP.

<!--?php
function check_file_exist($url){
    $handle = @fopen($url, 'r');
    if(!$handle){
        return false;
    }else{
        return true;
    }
}<p-->

$imgurl = "htttps://mydomain.com/images/img.png";
$exists = check_file_exist($imgurl);
if($exists){
    echo "file exists";
} else {
    echo "file not found";
}
?>

2. Using get_headers() function

Also, you can check if the URL is working or not by using the below custom function.

<!--?php
function url_exists($url){
   $headers=get_headers($url);
   if(stripos($headers[0],"200 OK")){
    return true;
   } else {
    return false;
   }
}<p-->

$imgurl = "htttps://mydomain.com/images/img.png";
$exists = url_exists($imgurl);
if($exists){
    echo "file exists";
} else {
    echo "file not found";
}
?>

3. Using cURL function

You can do the same task using cURL in PHP as shown in the below code:

<!--?php
function check_file_exist($url) {
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_NOBODY, true);
    curl_exec($ch);
    $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);<p-->

    if ($code == 200) {
        $status = true;
    } else {
        $status = false;
    }
    curl_close($ch);
    return $status;
}

$imgurl = "htttps://mydomain.com/images/img.png";
$exists = check_file_exist($imgurl);
if($exists){
    echo "file exists";
} else {
    echo "file not found";
}
?>

That’s it for today.
Thank you for reading. Happy Coding..!!