萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript 驗證 URL 格式:前端正則與後端 PHP 雙重防護

前端驗證(使用者體驗,非安全防線)

簡易版:HTML5 原生驗證


<form>
  <input type="url" name="url" placeholder="https://example.com" required>
  <button type="submit">送出</button>
</form>

瀏覽器自動檢查格式,但規則較寬鬆(允許 https://localhost 等)。

進階版:自訂正則


function isValidURL(str) {
  // RFC 3986 簡化版:協議 + 域名/IP + 可選埠/路徑/查詢/片段
  var pattern = /^(https?:\/\/)?/                    // 協議 (可選)
    + /(([a-zA-Z0-9-]+\.)+[a-zA-Z]{2,}|localhost)/  // 域名或 localhost
    + /(:\d+)?/                                      // 埠號
    + /(\/[^\s]*)?$/;                                // 路徑等
  return pattern.test(str);
}

// 測試
isValidURL('https://www.example.com');     // true
isValidURL('https://localhost:3000/path');  // true
isValidURL('ftp://example.com');           // false (非 http/https)
isValidURL('example.com');                 // true (允許無協議)
isValidURL('not a url');                   // false

嚴格版:必須含協議、合法域名


function isStrictURL(str) {
  var pattern = /^https?:\/\//i                              // 必須 http/https
    + /(?:[a-zA-Z0-9-]+\.)+[a-zA-Z]{2,}/                    // 域名
    + /(?::\d+)?/                                           // 可選埠
    + /(?:(?:\/|\\?|#)[^\s]*)?$/;                           // 路徑/查詢/錨點
  return pattern.test(str);
}

完整表單驗證範例


<form id="urlForm" onsubmit="return checkUrl()">
  <input type="text" id="url" name="url" placeholder="請輸入完整網址 (含 https://)">
  <span id="urlError" class="error" style="display:none;color:red"></span>
  <button type="submit">提交</button>
</form>

<script>
function checkUrl() {
  var url = document.getElementById('url').value.trim();
  var $err = document.getElementById('urlError');
  
  if (!url) { $err.textContent = '網址不可為空'; $err.style.display = 'block'; return false; }
  if (!isStrictURL(url)) { $err.textContent = '格式錯誤,需包含 https:// 或 https://'; $err.style.display = 'block'; return false; }
  
  $err.style.display = 'none';
  return true; // 允許提交
}
</script>

後端 PHP 驗證(安全防線)


 400, 'msg' => '無效的網址']));
}
// 進一步處理:file_get_contents、cURL 抓取、存入資料庫...

SSRF (Server-Side Request Forgery) 防護重點

  • 禁止存取內網 IP:10.x.x.x、172.16-31.x.x、192.168.x.x、127.0.0.1、169.254.x.x (metadata service)。
  • 禁止 file://、gopher://、dict:// 等非 HTTP 協議。
  • 使用允許清單域名、或代理伺服器統一發出請求。
  • 設定 cURL CURLOPT_FOLLOWLOCATION 限制重導向次數與域名。

現代前端:URL API 輔助解析


try {
  var u = new URL(input); // 必須含協議
  console.log('協議:', u.protocol);   // 'https:'
  console.log('主機:', u.hostname);   // 'example.com'
  console.log('埠:', u.port);         // '443' 或 ''
  console.log('路徑:', u.pathname);   // '/path'
  console.log('查詢:', u.search);     // '?a=1'
  console.log('雜湊:', u.hash);       // '#section'
} catch (e) {
  // 格式無效
}
copyright © 萬盛學電腦網 all rights reserved