php validate uri

Chack to see if a url or uri exists

Code 1



$statusCode = validate($_REQUEST['url']);
if ($statusCode==200)
  echo ‘Voila! URL ‘.$_REQUEST['url'].
  ’ exists, returned code is :.$statusCode;
  echo ‘Opps! URL ‘.$_REQUEST['url'].
  ’ does NOT exist, returned code is :.$statusCode;
function validateurl($url)
  // Initialize the handle
  $ch = curl_init();
  // Set the URL to be executed
  curl_setopt($ch, CURLOPT_URL, $url);
  // Set the curl option to include the header in the output
  curl_setopt($ch, CURLOPT_HEADER, true);
  // Set the curl option NOT to output the body content
  curl_setopt($ch, CURLOPT_NOBODY, true);
  /* Set to TRUE to return the transfer
  as a string of the return value of curl_exec(),
  instead of outputting it out directly */
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  // Execute it
  $data = curl_exec($ch);
  // Finally close the handle
  /* In this case, we’re interested in
  only the HTTP status code returned, therefore we
  use preg_match to extract it, so in the second element
  of the returned array is the status code */
  return $matches[1];

Code 2

An ulternate, regex only approach


$urlregex = "^(https?|ftp)\:\/\/";
// USER AND PASS (optional)
$urlregex .= "([a-z0-9+!*(),;?&=\$_.-]+(\:[a-z0-9+!*(),;?&=\$_.-]+)?@)?";
$urlregex .= "[a-z0-9+\$_-]+(\.[a-z0-9+\$_-]+)*";  // http://x = allowed (ex. http://localhost, http://routerlogin)
//$urlregex .= "[a-z0-9+\$_-]+(\.[a-z0-9+\$_-]+)+";  // http://x.x = minimum
//$urlregex .= "([a-z0-9+\$_-]+\.)*[a-z0-9+\$_-]{2,3}";  // http://x.xx(x) = minimum
//use only one of the above
// PORT (optional)
$urlregex .= "(\:[0-9]{2,5})?";
// PATH  (optional)
$urlregex .= "(\/([a-z0-9+\$_-]\.?)+)*\/?";
// GET Query (optional)
$urlregex .= "(\?[a-z+&\$_.-][a-z0-9;:@/&%=+\$_.-]*)?";
// ANCHOR (optional)
$urlregex .= "(#[a-z_.-][a-z0-9+\$_.-]*)?\$"; 
// check
if (eregi($urlregex, $url)) {echo "good";} else {echo "bad";}

Code 3

Another good example for url validation


* Validate URL
* Allows for port, path and query string validations
* @param    string      $url       string containing url user input
* @return   boolean     Returns TRUE/FALSE
function validateURL($url) {
	$pattern = '/^(([\w]+:)?\/\/)?'; //match http:// or ftp://, optional since ? (match 0 or 1x).
	$pattern.= '(([\d\w]|%[a-fA-f\d]{2,2})+(:([\d\w]|%[a-fA-f\d]{2,2})+)?@)?'; //match user:pass@
	$pattern.= '([\d\w][-\d\w]{0,253}[\d\w]\.)+[\w]{2,4}(:[\d]+)?'; //match ip or host
	$pattern.= '(\/([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)*'; //match filepath
	$pattern.= '(\?(&amp;?([-+_~.\d\w]|%[a-fA-f\d]{2,2})=?)*)?(#([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)?$/'; //after ? get
	return preg_match($pattern, $url);
$result = validateURL('');
print $result;

Candidate Code Suggestions

Add your suggestions and links here.