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

PHP 開發者必知的 10 個冷門實用技巧

     編輯:PHP 相關知識

1. IP 地址轉整數存儲: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 位元。

2. 郵箱域名驗證:checkdnsrr()

function isValidEmailDomain(string $email): bool {
    $domain = substr(strrchr($email, '@'), 1);
    return checkdnsrr($domain, 'MX') || checkdnsrr($domain, 'A');
}
// 攔截 user@gmial.com、user@localhost 等明顯錯誤域名

3. MySQL 4.1+ 必用 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 注入、重複執行效能提升 (解析/優化一次)、二進制協議傳輸更省頻寬。

4. 三元運算子鏈式簡化

$role = $user->isAdmin ? 'admin' : ($user->isEditor ? 'editor' : 'guest');
// PHP 7.0+ Null 合併運算子
$name = $input['name'] ?? $user->name ?? '匿名用戶';

5. 善用 PEAR / Packagist 現成輪子

造輪子前先搜尋:composer search "關鍵字"、Packagist、GitHub Topics。常用:league/flysystem (檔案系統抽象)、ramsey/uuid、carbon/carbon (日期時間)、symfony/console (CLI)。

6. highlight_file() 即時生成彩色代碼展示

<?php
// 除錯/分享代碼片段
highlight_file(__FILE__); // 當前檔案
// 或
highlight_string('<?php echo "Hello"; ?>');

警告:勿在生產環境暴露含敏感資訊 (DB 憑證、API Key) 的檔案。

7. 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。

8. 大文本欄位壓縮存儲:gzcompress() / gzuncompress()

$compressed = gzcompress($longText, 6); // 1-9 壓縮等級,6 平衡速度/比率
// 存入 BLOB/TEXT 欄位
// 讀取
$original = gzuncompress($row['compressed_content']);
// 典型文本壓縮率 70-90%,極大降低儲存成本與 I/O

不適用:需全文檢索、已壓縮格式 (圖片、視頻、ZIP)、極短字串 (開銷大於收益)。

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

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";
}

10. 深度理解魔術引號與 SQL 注入

magic_quotes_gpc (PHP 5.4 移除) 自動跳脫 '"\NULL,造成雙重跳脫、誤判、虛假安全感。永遠:

  1. 關閉魔術引號 (舊版)
  2. 使用預處理語句 (PDO/mysqli)
  3. 輸出時按上下文跳脫 (htmlspecialchars, json_encode, escapeshellarg)
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved