How to check if URL exists in PHP?
How to check if URL exists in PHP?
Let’s say you want to check if an URL exists. You want to do that with PHP because that is what you know, and you want to perform some savings into the database if that URL exists. This can be done in various ways which will work or not depending by case.
1st solution
We can do this by relying on http headers, normally if one URL gives a 200 http response code, it will be seen as success. However if this is something else, either the url does not exist or its an error on the other end. You can use the below example:
1 2 3 4 5 6 7 8 |
$url = 'http://www.example.com'; $array = get_headers($url); $string = $array[0]; if(strpos($string,"200")) { echo 'url exists'; } else { echo 'url does not exist'; } |
2nd solution
On some servers, you are not allowed to use CURL, but this can be used on a server that you have access and know it’s configuration:
1 2 3 4 |
function check_if_url_exists($url) { if (!$fp = curl_init($url)) return false; return true; } |
3rd solution
This one is similar to the first one, but using preg_match to pass true only if it matches the http code with 2xx value.
1 2 3 4 |
function check_if_url_exists($url) { $headers = @get_headers($url); return is_array($headers) ? preg_match('/^HTTP\/\d+\.\d+\s+2\d\d\s+.*$/',$headers[0]) : false; } |
Each given solution might/might not work depending on some given circumstances. It is your choice what you will be using for your projects.