首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

PHP URL 相關函式大全:編碼、解析、Header 獲取與 Meta 標籤提取

     編輯:PHP 綜合知識

Base64 編解碼:資料傳輸的基石

$str = 'This is an encoded string';
echo base64_encode($str);  // VGhpcyBpcyBhbiBlbmNvZGVkIHN0cmluZw==
echo base64_decode('VGhpcyBpcyBhbiBlbmNvZGVkIHN0cmluZw=='); // 還原

Base64 將二進位資料轉為可列印 ASCII,體積膨脹約 33%,常用於 Email 附件、JSON 傳輸二進位、URL 參數攜帶特殊字元等場景。

HTTP Header 獲取:get_headers()

$h1 = get_headers('https://example.com');
$h2 = get_headers('https://example.com', 1); // 關聯陣列模式
print_r($h2);
/*
Array(
  [0] => HTTP/1.1 200 OK
  [Server] => nginx
  [Content-Type] => text/html; charset=UTF-8
  ...
)
*/

第二參數 1 將回傳關聯陣列,方便直接取 $h2['Content-Type']。可用於檢測連結存活、重導向鏈、快取策略等。

Meta 標籤提取:get_meta_tags()

$meta = get_meta_tags('https://example.com');
/*
Array(
  [keywords] => SEO,關鍵字
  [description] => 頁面描述
  [generator] => WordPress 5.8
)
*/

快速抓取 SEO 資訊、CMS 指紋,適合爬蟲前置分析。

URL 組裝與解析

http_build_query():陣列轉查詢字串

$arr = ['c'=>'blog', 'a'=>'show', 'id'=>10, 'hello', 'world'];
echo http_build_query($arr);        // c=blog&a=show&id=10&0=hello&1=world
echo http_build_query($arr, 'pfx_'); // 數字索引加前綴:pfx_0=hello&pfx_1=world

API 串接時組裝 GET/POST 參數極為方便,自動處理 URL 編碼。

parse_url():URL 拆解

$url = 'https://user:pass@host.com/path?query=1#frag';
print_r(parse_url($url));
/*
Array(
  [scheme] => http
  [host] => host.com
  [user] => user
  [pass] => pass
  [path] => /path
  [query] => query=1
  [fragment] => frag
)
*/

不驗證 URL 合法性,僅拆解;不完整 URL 也能盡力解析。

URL 編碼四兄弟:差異在哪?

函式空格編碼依據標準適用場景
urlencode()+application/x-www-form-urlencoded表單 POST、舊版 API
rawurlencode()%20RFC 3986 (URI 標準)現代 REST API、URL 路徑段
urldecode()解 + 為空格對應 urlencode解析表單資料
rawurldecode()解 %20 為空格對應 rawurlencode解析標準 URI
$url = 'https://example.com?q=hello world';
echo urlencode($url);    // http%3A%2F%2Fexample.com%3Fq%3Dhello+world
echo rawurlencode($url); // http%3A%2F%2Fexample.com%3Fq%3Dhello%20world

黃金法則:建構 URL 時用 rawurlencode,解析表單資料用 urldecode,避免空格編碼不一致導致簽名驗證失敗。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved