判斷url連接是否有效的幾種方法

前提

須要判斷遠程URL是否有效,遠程url包括遠程圖片,網頁,視頻等等元素javascript

解決辦法:


使用PHP解決
  1. 使用file_get_contents函數,不過優缺點若是url沒法訪問,會出現終止程序問題
  2. 使用curl返回,而後判斷是否正確執行
  3. 使用get_headers函數,根據HTTP返回值查看是否有200

使用js解決:
  1. 使用原生的js函數ActiveXObject,僅支持ie內核的瀏覽器
  2. 使用jq擴展

本文主要介紹PHP解決辦法中的第三種,這個方法不多用到,可是感受又起來還不錯。php

get_headers須要支持
  1. php_openssl支持  查看phpinfo看看是否開啓
  2. allow_url_fopen=on  修改php.ini,運行使用遠程打開


函數介紹

array get_headers ( string $url [, int $format ] )java

get_headers() 返回一個數組,包含有服務器響應一個 HTTP 請求所發送的標頭。若是失敗則返回 FALSE 併發出一條 E_WARNING 級別的錯誤信息。jquery

若是將可選的 format 參數設爲 1,則 get_headers() 會解析相應的信息並設定數組的鍵名。 例如:


數組

簡單的例子:瀏覽器

<?php 
$url = "http://cn.php.net/images/php.gif"; 
$array = get_headers($url,1); 
if(preg_match('/200/',$array[0])){ 
    echo "<pre/>"; 
    print_r($array); 
}else{ 
    echo "無效url資源!"; 
}

解釋:判斷遠程圖片ur是否有效,根據返回值HTTP中是否有200信息,判斷是不是有效url資源服務器

測試結果:


能夠看到正確返回 -----------------------測試ok
併發


優勢缺點:

須要allow_url_fopen=on  開啓,有點和file_get_contents函數使用條件相似,可是返回值比較少,能夠使用function_exists判斷該方法是否能夠使用curl

js方法:

解決方案一: XMLHTTP方案jsp

<script language= "javascript">
function getURL(url) {
        var xmlhttp = new ActiveXObject( "Microsoft.XMLHTTP");
        xmlhttp.open("GET", url, false);
        xmlhttp.send();
        if(xmlhttp.readyState==4) {
            if(xmlhttp.Status != 200) alert("不存在");
            return xmlhttp.Status==200;
        }
        return false;
}
</script>
<a href= "http://www.oschina.net/aaa.jsp "  onclick= "return  getURL(this.href)"> oschina </a>

缺點: 使用ActiveXObject, 因此是IE Only. 非IE內核瀏覽器不可用.

解決方案二: jQuery擴展
jQuery插件:http://plugins.jquery.com/project/linkchecker
Demo:http://sidashin.ru/linkchecker/
代碼只要這樣幾句:

<script src="jquery.js"></script>
<script src="jquery.linkchecker.js"></script>
<script type="text/javascript">
$(document).ready( function() {   
    $.linkChecker({query : 'a', linksAtOnce : 2});  
});
</script>
相關文章
相關標籤/搜索