ip2long() / long2ip()$ip = '192.168.1.100';
$int = ip2long($ip); // 3232235876 (無符號) 或 -1062731420 (有符號 32 位)
// 儲存用 UNSIGNED INT (4 bytes) 替代 CHAR(15) (15 bytes),索引更小、範圍查詢 (BETWEEN) 極快
// 還原
echo long2ip($int); // 192.168.1.100
注意:IPv6 需用 inet_pton()/inet_ntop() 處理 128 位元。
checkdnsrr()function isValidEmailDomain(string $email): bool {
$domain = substr(strrchr($email, '@'), 1);
return checkdnsrr($domain, 'MX') || checkdnsrr($domain, 'A');
}
// 攔截 user@gmial.com、user@localhost 等明顯錯誤域名
mysqli 預處理語句$stmt = $mysqli->prepare('SELECT id, name FROM users WHERE email = ? AND status = ?');
$stmt->bind_param('si', $email, $status);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) { /* ... */ }
$stmt->close();
防 SQL 注入、重複執行效能提升 (解析/優化一次)、二進制協議傳輸更省頻寬。
$role = $user->isAdmin ? 'admin' : ($user->isEditor ? 'editor' : 'guest');
// PHP 7.0+ Null 合併運算子
$name = $input['name'] ?? $user->name ?? '匿名用戶';
造輪子前先搜尋:composer search "關鍵字"、Packagist、GitHub Topics。常用:league/flysystem (檔案系統抽象)、ramsey/uuid、carbon/carbon (日期時間)、symfony/console (CLI)。
highlight_file() 即時生成彩色代碼展示<?php
// 除錯/分享代碼片段
highlight_file(__FILE__); // 當前檔案
// 或
highlight_string('<?php echo "Hello"; ?>');
警告:勿在生產環境暴露含敏感資訊 (DB 憑證、API Key) 的檔案。
error_reporting(0) 生產環境隱藏錯誤細節<?php
// 入口檔案最頂部
error_reporting(0);
ini_set('display_errors', '0');
ini_set('log_errors', '1');
ini_set('error_log', '/var/log/php/error.log');
防止堆疊追蹤、SQL、路徑洩露給攻擊者。開發環境保持 E_ALL。
gzcompress() / gzuncompress()$compressed = gzcompress($longText, 6); // 1-9 壓縮等級,6 平衡速度/比率
// 存入 BLOB/TEXT 欄位
// 讀取
$original = gzuncompress($row['compressed_content']);
// 典型文本壓縮率 70-90%,極大降低儲存成本與 I/O
不適用:需全文檢索、已壓縮格式 (圖片、視頻、ZIP)、極短字串 (開銷大於收益)。
function parseName(string $fullName, string &$firstName, string &$lastName): bool {
$parts = explode(' ', trim($fullName), 2);
if (count($parts) !== 2) return false;
[$firstName, $lastName] = $parts;
return true;
}
if (parseName('張 三', $first, $last)) {
echo "First: $first, Last: $last";
}
magic_quotes_gpc (PHP 5.4 移除) 自動跳脫 '"\NULL,造成雙重跳脫、誤判、虛假安全感。永遠:
htmlspecialchars, json_encode, escapeshellarg)