$ip = '192.168.1.100';
$long = ip2long($ip); // 3232235876
$ip2 = long2ip($long); // '192.168.1.100'
// 數據庫存 BIGINT UNSIGNED,索引極快,範圍查詢簡單
// WHERE ip_long BETWEEN ip2long('192.168.1.0') AND ip2long('192.168.1.255')
節省 75% 存儲空間(15 字節 char → 4 字節 int),加速排序/篩選。
function isEmailDeliverable(string $email): bool {
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) return false;
$domain = explode('@', $email)[1];
return checkdnsrr($domain, 'MX');
}
比單純正則更接近真實可投遞性。
$stmt = $pdo->prepare('SELECT * FROM users WHERE email = ? AND status = 1');
$stmt->execute([$email]);
$user = $stmt->fetch();
```
- 徹底防 SQL 注入
- 重複執行時服務端緩存执行計劃,提升 20%-30% 性能
$status = $user->isActive() ? 'active' : 'inactive';
$page = $_GET['p'] ?? 1; // PHP 7+ null 合併運算符
$limit = min(max((int)$_GET['limit'], 1), 100);
代碼緊湊、可讀性強,避免冗長 if/else。
Composer 生態成熟,優先搜索現成方案。
<?php
// show_source.php
$file = __DIR__ . '/' . basename($_GET['file'] ?? '');
if (is_file($file) && pathinfo($file, PATHINFO_EXTENSION) === 'php') {
highlight_file($file); // 自動輸出帶行號高亮 HTML
} else {
http_response_code(404);
echo 'File not found';
}
調試、代碼分享、文檔生成極其方便。**注意過濾敏感文件路徑**。
<?php
// 入口文件第一行
error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED & ~E_STRICT);
ini_set('display_errors', '0');
ini_set('log_errors', '1');
ini_set('error_log', __DIR__ . '/../logs/php_errors.log');
防止 SQL、路徑、堆棧信息洩露給用戶,統一寫入日誌供運維分析。
$bigText = str_repeat('Lorem ipsum ', 10000); // ~120KB
$compressed = gzcompress($bigText, 9); // ~90% 壓縮比
// 存入 BLOB/TEXT 字段
$restored = gzuncompress($compressed);
適用于日志、文章全文、JSON 配置等大字段,節省 90% 存儲。**全文搜索場景除外**。
function stats(array $data, int &$sum, float &$avg, int &$max): void {
$sum = array_sum($data);
$avg = $sum / count($data);
$max = max($data);
}
$numbers = [3, 7, 2, 9, 5];
stats($numbers, $sum, $avg, $max);
// $sum=26, $avg=5.2, $max=9
避免返回嵌套數組,語義清晰。PHP 8.1+ 也可用 `#[ReturnTypeWillChange]` 屬性或直接返回對象/數組。
這 10 招涵蓋**存儲優化、驗證增強、安全防護、性能調優、代碼簡化、生態利用、調試工具、錯誤控制、壓縮存儲、多返回值**——掌握它們,即可從「寫出能跑的代碼」進階到「寫出健壯、高效、可維護的專業代碼」。