How to check if a file exists from a URL in 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
Here, we will create a custom function to check if a file exists on a remote server or not using fopen() function in PHP.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | <?php function check_file_exist($url){ $handle = @fopen($url, 'r'); if(!$handle){ return false; }else{ return true; } } $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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | <?php function url_exists($url){ $headers=get_headers($url); if(stripos($headers[0],"200 OK")){ return true; } else { return false; } } $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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | <?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); 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..!!