萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 開發者必知的 10 個進階技巧與冷知識

前言

PHP 看似簡單,實則藏有許多能顯著提升效能、安全性與開發效率的技巧。本文整理 10 個資深開發者常用但新手易忽略的進階知識點。

1. IP 地址轉整數儲存:ip2long() / long2ip()

IPv4 地址轉為無號整數,儲存空間從 `CHAR(15)` 15 字節降至 `INT UNSIGNED` 4 字節(節省 73%),範圍查詢與索引效能大幅提升。

<?php
$ip = '192.168.1.100';
$int = ip2long($ip);        // 3232235876 (有號可能為負)
$uint = sprintf('%u', $int); // 3232235876 (無號字串)

// 資料庫儲存建議:INT UNSIGNED
// 查詢某 IP 是否在 CIDR 範圍內
function ipInRange(string $ip, string $cidr): bool {
    [$range, $mask] = explode('/', $cidr);
    $ipInt = ip2long($ip);
    $rangeInt = ip2long($range);
    $maskInt = ~((1 << (32 - $mask)) - 1);
    return ($ipInt & $maskInt) === ($rangeInt & $maskInt);
}

var_dump(ipInRange('192.168.1.50', '192.168.1.0/24')); // true
?>

注意: IPv6 需使用 `inet_pton()` / `inet_ntop()` 配合 `VARBINARY(16)` 儲存。

2. Email 域名驗證:checkdnsrr()

語法驗證不足,結合 DNS MX 記錄檢查確認域名真實可收信:

<?php
function validateEmailWithMx(string $email): bool {
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        return false;
    }
    
    $domain = substr(strrchr($email, '@'), 1);
    // 檢查 MX 記錄(郵件交換器)
    if (checkdnsrr($domain, 'MX')) {
        return true;
    }
    
    // 降級檢查 A 記錄(某些域名無 MX 但有 A 記錄也可收信)
    return checkdnsrr($domain, 'A');
}

// 可攔截 "joeuser@wwwphp.net" 這類拼錯域名
var_dump(validateEmailWithMx('test@gmail.com'));      // true
var_dump(validateEmailWithMx('test@notexist.xyz'));   // false
?>

3. 棄用 mysql_*,改用 mysqli_* 或 PDO

PHP 5.5 棄用、7.0 移除 `mysql_*`。`mysqli` 提供:

  • 預處理語句:防 SQL 注入、重複執行效能佳
  • 物件導向介面:更現代、可讀性高
  • 多重查詢:`multi_query()`
  • 交易支援:`begin_transaction()`、`commit()`、`rollback()`
<?php
// 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()) { ... }

// PDO 範例(推薦:資料庫抽象層)
$stmt = $pdo->prepare("SELECT * FROM users WHERE email = :email");
$stmt->execute([':email' => $email]);
$users = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>

4. 善用三元運算子與 Null 合併運算子

<?php
// 三元運算子
$status = $user->isActive ? '啟用' : '停用';

// Null 合併運算子 (PHP 7+) - 取代 isset() 檢查
$name = $input['name'] ?? '訪客';        // $_GET['name'] 不存在則用 '訪客'
$config = $config['db']['host'] ?? 'localhost'; // 多層級鏈式

// Elvis 運算子 ?: (PHP 5.3+)
$value = $expr ?: 'default'; // $expr 為 truthy 時用 $expr,否則 'default'
?>

5. 善用 PEAR / Packagist (Composer) 避免重造輪子

現代 PHP 開發核心:Composer + Packagist(PEAR 已不再主流)。

# 常用優質套件
composer require guzzlehttp/guzzle      # HTTP Client
composer require monolog/monolog        # 記錄器
composer require phpmailer/phpmailer    # Email 發送
composer require ramsey/uuid            # UUID 生成
composer require vlucas/phpdotenv       # 環境變數管理
composer require league/flysystem       # 檔案系統抽象
composer require doctrine/dbal          # 資料庫抽象層

6. 原始碼高亮輸出:highlight_file() / highlight_string()

<?php
// 顯示檔案高亮原始碼(除錯、教學、分享適用)
highlight_file(__FILE__); // 當前檔案
// highlight_file('path/to/script.php');

// 字串高亮
$code = '';
highlight_string($code);

// ⚠️ 安全警告:勿暴露含密碼、金鑰的設定檔
?>

7. 生產環境關閉錯誤顯示:error_reporting(0)

<?php
// 生產環境入口檔案最開頭
error_reporting(0);
ini_set('display_errors', '0');
ini_set('log_errors', '1');
ini_set('error_log', __DIR__ . '/logs/php-error.log');

// 開發環境
error_reporting(E_ALL);
ini_set('display_errors', '1');
?>

防止敏感資訊(SQL、路徑、堆疊追蹤)洩露給使用者。

8. 大字串壓縮儲存:gzcompress() / gzuncompress()

適用於 BLOB/TEXT 欄位儲存 JSON、HTML、日誌等可壓縮資料:

<?php
$largeJson = json_encode($bigDataArray);
$compressed = gzcompress($largeJson, 6); // 壓縮等級 1-9,6 平衡速度/比率

// 儲存 $compressed 到 BLOB 欄位

// 讀取還原
$original = gzuncompress($compressed);
$data = json_decode($original, true);

// 壓縮率通常 70-90%(文字資料)
echo "原始: " . strlen($largeJson) . " bytes\n";
echo "壓縮: " . strlen($compressed) . " bytes (" . round(strlen($compressed)/strlen($largeJson)*100, 1) . "%)\n";
?>

例外: 需全文搜尋的欄位勿壓縮。

9. 參考傳遞實現多返回值

<?php
function getUserStats(int $userId, int &$postCount, int &$commentCount, float &$avgScore): bool {
    // 查詢資料庫...
    $postCount = 42;
    $commentCount = 128;
    $avgScore = 4.7;
    return true; // 成功指標
}

$posts = $comments = 0;
$avg = 0.0;
if (getUserStats(123, $posts, $comments, $avg)) {
    echo "文章: $posts, 留言: $comments, 平均分: $avg";
}

// 現代替代:回傳物件/陣列/DTO(更清晰)
function getUserStatsDto(int $userId): ?UserStatsDto { ... }
?>

10. 徹底理解 Magic Quotes 與 SQL Injection 防禦

Magic Quotes 已在 PHP 5.4 移除(自動對 GET/POST/COOKIE 加反斜線)。

正確防禦:預處理語句

<?php
// ✅ 正確:參數化查詢
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = ?");
$stmt->execute([$username]);

// ❌ 錯誤:字串拼接(即使用 addslashes/real_escape_string 也不完全安全)
$sql = "SELECT * FROM users WHERE username = '" . $username . "'";

關鍵原則

  1. 永遠使用預處理語句(Prepared Statements)
  2. 輸出到 HTML 時用 `htmlspecialchars()`
  3. 輸出到 JS 時用 `json_encode()`
  4. 輸出到 Shell 時用 `escapeshellarg()` / `escapeshellcmd()`
  5. 輸出到 SQL 時用**預處理**,不手動跳脫

總結:現代 PHP 開發者檢核表

項目現代做法避免做法
IP 儲存`ip2long()` + `INT UNSIGNED``VARCHAR(15)` 字串
Email 驗證`filter_var()` + `checkdnsrr('MX')`單純 Regex
資料庫存取PDO / mysqli + 預處理`mysql_*` / 字串拼接
預設值處理Null 合併 `??` / Elvis `?:``isset()` 多層巢狀
套件管理Composer + Packagist手動 include / PEAR
錯誤處理生產關閉顯示、記錄日誌直接顯示錯誤給用戶
大資料儲存`gzcompress()` + BLOB直接存長文字
多返回值回傳 DTO/陣列/物件參考傳遞 `&$var`
SQL 注入防禦預處理語句Magic Quotes / 手動跳脫
copyright © 萬盛學電腦網 all rights reserved