检查url是否有效的最佳方法

我想用PHP来检查,如果存储在$myoutputvariables中的string包含有效的链接语法,或者它只是一个正常的文本。 我正在寻找的function或解决scheme应该能够识别所有链接格式,包括具有GET参数的链接格式。

一个解决scheme,在许多网站上build议,实际上查询string(使用CURL或file_get_contents()函数)是不可能在我的情况下,我想避免它。

我想过正则expression式或其他解决scheme。

您可以使用本机filtervalidation程序

 filter_var($url, FILTER_VALIDATE_URL); 

将值作为URL进行validation(根据» http://www.faqs.org/rfcs/rfc2396 ),可选地包含所需的组件。 请注意,有效的URL可能不会指定HTTP协议http://,因此可能需要进一步的validation来确定URL使用期望的协议,例如ssh://或mailto :. 请注意,该function只会发现ASCIIurl是有效的; 国际化域名(包含非ASCII字符)将失败。

例:

 if (filter_var($url, FILTER_VALIDATE_URL) === FALSE) { die('Not a valid URL'); } 

这里是我在那里find的最好的教程:

http://www.w3schools.com/php/filter_validate_url.asp

 <?php $url = "http://www.qbaki.com"; // Remove all illegal characters from a url $url = filter_var($url, FILTER_SANITIZE_URL); // Validate url if (!filter_var($url, FILTER_VALIDATE_URL) === false) { echo("$url is a valid URL"); } else { echo("$url is not a valid URL"); } ?> 

可能的标志:

 FILTER_FLAG_SCHEME_REQUIRED - URL must be RFC compliant (like http://example) FILTER_FLAG_HOST_REQUIRED - URL must include host name (like http://www.example.com) FILTER_FLAG_PATH_REQUIRED - URL must have a path after the domain name (like www.example.com/example1/) FILTER_FLAG_QUERY_REQUIRED - URL must have a query string (like "example.php?name=Peter&age=37") 

使用filter_var()将失败的非ASCII字符的url,例如( http://pt.wikipedia.org/wiki/Guimarães )。 以下函数在调用filter_var()之前对所有非A​​SCII字符(例如http://pt.wikipedia.org/wiki/Guimar%C3%A3es )进行编码。

希望这有助于某人。

 <?php function validate_url($url) { $path = parse_url($url, PHP_URL_PATH); $encoded_path = array_map('urlencode', explode('/', $path)); $url = str_replace($path, implode('/', $encoded_path), $url); return filter_var($url, FILTER_VALIDATE_URL) ? true : false; } // example if(!validate_url("http://somedomain.com/some/path/file1.jpg")) { echo "NOT A URL"; } else { echo "IS A URL"; } 

您可以使用此function,但如果网站离线,它将返回false。

  function isValidUrl($url) { $url = parse_url($url); if (!isset($url["host"])) return false; return !(gethostbyname($url["host"]) == $url["host"]); } 
 function is_url($uri){ if(preg_match( '/^(http|https):\\/\\/[a-z0-9_]+([\\-\\.]{1}[a-z_0-9]+)*\\.[_a-z]{2,5}'.'((:[0-9]{1,5})?\\/.*)?$/i' ,$uri)){ return $uri; } else{ return false; } } 

另一种检查给定的URL是否有效的方法是尝试访问它,下面的函数将从给定的URL获取头,这将确保URL是有效的,并且 Web服务器是活着的:

 function is_url($url){ $response = array(); //Check if URL is empty if(!empty($url)) { $response = get_headers($url); } return (bool)in_array("HTTP/1.1 200 OK", $response, true); /*Array ( [0] => HTTP/1.1 200 OK [Date] => Sat, 29 May 2004 12:28:14 GMT [Server] => Apache/1.3.27 (Unix) (Red-Hat/Linux) [Last-Modified] => Wed, 08 Jan 2003 23:11:55 GMT [ETag] => "3f80f-1b6-3e1cb03b" [Accept-Ranges] => bytes [Content-Length] => 438 [Connection] => close [Content-Type] => text/html )*/ } 

我个人想在这里使用正则expression式。 贝娄码完全为我工作。

 $baseUrl = url('/'); // for my case https://www.xrepeater.com $posted_url = "home"; // Test with one by one /*$posted_url = "/home"; $posted_url = "xrepeater.com"; $posted_url = "www.xrepeater.com"; $posted_url = "http://www.xrepeater.com"; $posted_url = "https://www.xrepeater.com"; $posted_url = "https://xrepeater.com/services"; $posted_url = "xrepeater.dev/home/test"; $posted_url = "home/test";*/ $regularExpression = "((https?|ftp)\:\/\/)?"; // SCHEME Check $regularExpression .= "([a-z0-9+!*(),;?&=\$_.-]+(\:[a-z0-9+!*(),;?&=\$_.-]+)?@)?"; // User and Pass Check $regularExpression .= "([a-z0-9-.]*)\.([az]{2,3})"; // Host or IP Check $regularExpression .= "(\:[0-9]{2,5})?"; // Port Check $regularExpression .= "(\/([a-z0-9+\$_-]\.?)+)*\/?"; // Path Check $regularExpression .= "(\?[a-z+&\$_.-][a-z0-9;:@&%=+\/\$_.-]*)?"; // GET Query String Check $regularExpression .= "(#[a-z_.-][a-z0-9+\$_.-]*)?"; // Anchor Check if(preg_match("/^$regularExpression$/i", $posted_url)) { if(preg_match("@^http|https://@i",$posted_url)) { $final_url = preg_replace("@(http://)+@i",'http://',$posted_url); // return "*** - ***Match : ".$final_url; } else { $final_url = 'http://'.$posted_url; // return "*** / ***Match : ".$final_url; } } else { if (substr($posted_url, 0, 1) === '/') { // return "*** / ***Not Match :".$final_url."<br>".$baseUrl.$posted_url; $final_url = $baseUrl.$posted_url; } else { // return "*** - ***Not Match :".$posted_url."<br>".$baseUrl."/".$posted_url; $final_url = $baseUrl."/".$final_url; } } 

鉴于filter_var()需要http://的问题,我使用:

$is_url = filter_var($filename, FILTER_VALIDATE_URL) || array_key_exists('scheme', parse_url($filename));