How to Validate a URL with PHP

A simple function using PHP and CURL that checks whether a URL is valid or not, by returning true or false.

This function has been adapted from a response to a similar question on Stack Overflow.

If you’re using WordPress this function can be added to functions.php. The function accepts a passed parameter (the URL) and checks if it is valid or not, then returns a true or false value depending on the outcome:

function validate_url($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;
}

If you’re using WordPress and want to check if a media file on your site is valid, you might want to check if the URL is relative first, and prefix it with your site URL if it is. See adapted version below which will check this first:

function validate_url($url){
	//check if media url is relative (starts with '/wp-content'), if so append site url so we have a full url
	if( substr( $url, 0, 11 ) === "/wp-content" ){ //0,11 represents 1st and last char of the string
		$site_url = site_url();
		$url = $site_url .= $url;
	}
	//if url is valid return true, else false
	$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;
}

To use the function simply call by with a passed parameter like so:

$url = 'http://dragoncode.co.uk/';
$valid_url = validate_url($url);

Want to do something based on whether it returns true or false? Here’s how:

if(validate_url($url) === true){ //if url is valid...
	//do something (true)
} else
	//do something else (false)
}	

Comments

Whether you have feedback, a question, want to share your opinion, or simply want to say thank you - we welcome comments! Please read the disclaimer.