$str = 'This is an encoded string';
echo base64_encode($str); // VGhpcyBpcyBhbiBlbmNvZGVkIHN0cmluZw==
echo base64_decode('VGhpcyBpcyBhbiBlbmNvZGVkIHN0cmluZw=='); // 還原
Base64 將二進位資料轉為可列印 ASCII,體積膨脹約 33%,常用於 Email 附件、JSON 傳輸二進位、URL 參數攜帶特殊字元等場景。
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']。可用於檢測連結存活、重導向鏈、快取策略等。
get_meta_tags()$meta = get_meta_tags('https://example.com');
/*
Array(
[keywords] => SEO,關鍵字
[description] => 頁面描述
[generator] => WordPress 5.8
)
*/
快速抓取 SEO 資訊、CMS 指紋,適合爬蟲前置分析。
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 也能盡力解析。
| 函式 | 空格編碼 | 依據標準 | 適用場景 |
|---|---|---|---|
urlencode() | + | application/x-www-form-urlencoded | 表單 POST、舊版 API |
rawurlencode() | %20 | RFC 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,避免空格編碼不一致導致簽名驗證失敗。