» Programming » PHP » Validators

Validate URL


1
2
3
4
5
6
7
8
9
10
11
12
13
14
function validate_url($url, $ftp=false) {
  if ($ftp) {
    $regex = "((https?|ftp)\:\/\/)?"; // SCHEME 
  } else {
    $regex = "((https?)\:\/\/)?"; // SCHEME 
  }
  $regex .= "([a-z0-9+!*(),;?&=\$_.-]+(\:[a-z0-9+!*(),;?&=\$_.-]+)?@)?"; // User and Pass 
  $regex .= "([a-z0-9-.]*)\.([a-z]{2,3})"; // Host or IP 
  $regex .= "(\:[0-9]{2,5})?"; // Port 
  $regex .= "(\/([a-z0-9+%\$_-]\.?)+)*\/?"; // Path  
  $regex .= "(\?[a-z+&\$_.-][a-z0-9;:@&%=+\/\$_.-]*)?"; // GET Query 
  $regex .= "(\#[a-z0-9;:@&%=+\/\$_.-]*)?"; // Anchor 
  return (preg_match("/^$regex$/i", $url) === 1);
}