2010-01-13 132 views
98

我想用PHP来检查,如果存储在$myoutput变量中的字符串包含有效的链接语法,或者它只是一个普通的文本。我正在寻找的功能或解决方案应能识别所有链接格式,包括带有GET参数的链接格式。最好的方法来检查一个URL是否有效

许多网站上建议的解决方案实际上查询字符串(使用CURL或file_get_contents()函数)在我的情况下是不可能的,我想避免它。

我想过正则表达式或其他解决方案。

+0

使用curl或得到它的HTTP内容可能会很慢,如果你想要更多的东西迅速和几乎一样可靠的,考虑在主机名上使用gethostbyaddr()。如果它解析为IP,那么它可能有一个网站。当然这取决于你的需求。 – TravisO 2010-01-13 18:28:29

回答

198

可以使用天然Filter Validator

filter_var($url, FILTER_VALIDATE_URL); 

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

例子:

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

它也允许像'http:// example'这样的url(thik'localhost'是一个url) – raveren 2011-10-14 13:23:57

+5

@Raveren预期的行为,因为这些是有效的URL。 – Gordon 2011-10-14 13:38:56

+6

请注意'FILTER_VALIDATE_URL'不会验证url的协议。所以'ssh://','ftp://'等会通过。 – Seph 2014-05-10 14:03:25

4
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; 
    } 
} 
+2

那么怎么样:'http:// 192.168.1.12'或'http:// 192.168.1.12/some-page'? – Haudegen 2016-03-01 13:20:24

2

您可以使用此功能,但如果网站下线的将返回false。

function isValidUrl($url) { 
    $url = parse_url($url); 
    if (!isset($url["host"])) return false; 
    return !(gethostbyname($url["host"]) == $url["host"]); 
} 
6

这是我在那儿找到的最好的教程:

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") 
1

检查,如果给定的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 
)*/ 
    } 
+0

好主意。如果服务器使用HTTP/1.0或HTTP/2.0,或者返回重定向,这将失败。 – iblamefish 2017-02-23 08:16:10

+0

是的,这是一个起点,可以轻松完成进一步的改进。 – bodi0 2017-02-23 08:31:16

5

使用filter_var()将与非ASCII字符,例如网址失败(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"; 
} 
0

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

$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+!*(),;?&=\$_.-]+)[email protected])?"; // User and Pass Check 
$regularExpression .= "([a-z0-9-.]*)\.([a-z]{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://)[email protected]",'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; } 
} 
1

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

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

相关问题