Check the Existence of Remote URL in PHP

Here, existence URL means whether the requesting URL is available on the server or not. In this quick snippet, we will see how to check URL existence using PHP. Here, I am going to give two different ways to check the URL existence and you may use any of the methods depending on your case.

Using PHP Function get_headers:

PHP has an inbuilt function named get_headers() which helps to fetch all the headers sent by the server in the response of a given HTTP request. From this header information, you can check whether the response code is 200 (If the given URL available) or 404 (If the given URL doesn’t available).

<?php
function urlExists($url) {
	$headers = @get_headers($url);
	if($headers &amp;&amp; strpos( $headers[0], '200')) {
		return "URL Exists";
	} else {
		return "URL Not Exists";
	}
}
echo urlExists('http://www.domain.com/');

Using cURL:

You may also check whether the given URL is available or not by using the cURL like an example code given below,

<?php
function urlExists($url) {
	$url = filter_var($url, FILTER_VALIDATE_URL);

	/* Open curl connection */
	$handle = curl_init($url);

	/* Set curl parameter */
	curl_setopt_array($handle, array(
		CURLOPT_NOBODY => TRUE,
		CURLOPT_HEADER => TRUE,
		CURLOPT_RETURNTRANSFER => TRUE
	));

	curl_exec($handle);
	
	$httpCode = curl_getinfo($handle, CURLINFO_HTTP_CODE);

	/* Check for 200 (URL is found). */
	if($httpCode == 200) {
		return "URL Exists";
	} else {
		return "URL Not Exists";
	}

	/* Close curl connection */
	curl_close($handle);
}

echo urlExists('http://www.domain.com');

In the above code, I have set CURLOPT_NOBODY as TRUE. Because we just want to check for the connection and not to fetch the whole body.

Hope this helps.

Leave a Reply

Your email address will not be published. Required fields are marked *