首页 > php开发 > php验证URL是否合法的函数

php验证URL是否合法的函数

验证URL有两种一种是利用正则表达式来验证URL是不是合适url规则了,另一个是利用函数来访问指定url看看是否可正常访问了,如果能正常访问自然就是合法的url地址了.

例子1,代码如下:

<?php 
function isValidUrl($url) {
    $patern = '/^http[s]?:\/\/'.  
        '(([0-9]{1,3}\.){3}[0-9]{1,3}'.   // IP形式的URL- 199.194.52.184  
        '|'.                               // 允许IP和DOMAIN(域名)  
        '([0-9a-z_!~*\'()-]+\.)*'.         // 三级域验证- www.  
        '([0-9a-z][0-9a-z-]{0,61})?[0-9a-z]\.'.     // 二级域验证  
        '[a-z]{2,6})'.        // 顶级域验证.com or .museum  
        '(:[0-9]{1,4})?'.        // 端口- :80  
        '((\/\?)|'.         / 如果含有文件对文件部分进行校验  
        '(\/[0-9a-zA-Z_!~\*\'\(\)\.;\?:@&=\+\$,%#-\/]*)?)$/'; 
    if(!preg_match($patern, $url)) { 
        die( '您输入的URL格式有问题,请检查!'); 
    } 
}

例子2,上面的例子只是验证url是不是正常的不代表是否可以访问了,我们可以使用如curl函数进行方法,代码如下:

$url = "http://www.phprm.com "; 
$curl = curl_init($url); 
curl_setopt($curl, CURLOPT_NOBODY, true); 
$result = curl_exec($curl); 
if ($result !== false)  
{ 
  $statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);   
  if ($statusCode == 404)  
  { 
    echo "URL Not Exists" 
  } 
  else 
  { 
     echo "URL Exists"; 
  }  
} 
else 
{ 
  echo "URL not Exists"; 
}

除了这个函数还可以使用php的很多函数如 file、file_get_contents()、fopen函数来进行检测了.


永久链接:http://www.phprm.com/develop/fs8980.html

转载随意!带上文章地址吧。

标签:php验证url php合法函数

发表留言