php驗證URL是否合法的函數

來源:互聯網
上載者:User

例子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.111cn.net ";
$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函數來進行檢測了。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.