Home > php教程 > php手册 > body text

php验证URL是否合法的函数

WBOY
Release: 2016-06-02 09:13:36
Original
941 people have browsed it

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

例子1

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

例子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";
}
Copy after login

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


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!