本文整理自實際開發過程中的關鍵知識點,涵蓋 HTTP 標頭操作、靜態變數行為、遞歸函數設計、靜態/動態綁定差異、PHP 運行模式比較、變數命名慣例、JSON 中文處理、CORS 跨域與 CodeIgniter HTTPS 強制等實用技巧。
header() 必須在任何輸出之前呼叫。常見用途:
<?php
// 編碼與內容類型
header('Content-Type: text/html; charset=utf-8');
header('Content-Type: application/json'); // API 回應
header('Content-Type: application/pdf'); // PDF 下載
header('Content-Type: image/jpeg'); // 圖片輸出
// HTTP 狀態碼
header('HTTP/1.1 200 OK');
header('HTTP/1.1 404 Not Found');
header('HTTP/1.1 301 Moved Permanently'); // 永久重導
header('Location: https://example.com/new-url'); // 重導向
header('Refresh: 5; url=https://example.com'); // 延遲跳轉
// 快取控制
header('Cache-Control: no-cache, no-store, max-age=0, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Pragma: no-cache');
// 檔案下載
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="export.xlsx"');
header('Content-Transfer-Encoding: binary');
readfile('export.xlsx');
// HTTP 基本認證
header('HTTP/1.1 401 Unauthorized');
header('WWW-Authenticate: Basic realm="Admin Area"');
?>
<?php
function counter() {
static $count = 0; // 僅初始化一次
return $count++;
}
echo counter(); // 0
echo counter(); // 1
echo counter(); // 2
// 遞歸應用:計算階乘
function factorial($n) {
static $cache = [0 => 1, 1 => 1];
if (isset($cache[$n])) return $cache[$n];
return $cache[$n] = $n * factorial($n - 1);
}
?>
特性:僅在函數作用域存在、跨呼叫保持值、不汙染全域命名空間。
<?php
$records = [
['firmware' => 'f1', 'version' => '1'],
['firmware' => 'f1', 'version' => '2'],
['firmware' => 'f1', 'version' => '3'],
['firmware' => 'f2', 'version' => '1'],
['firmware' => 'f2', 'version' => '2'],
];
$grouped = [];
foreach ($records as $row) {
$grouped[$row['firmware']][] = $row['version'];
}
/*
結果:
[
'f1' => ['1', '2', '3'],
'f2' => ['1', '2'],
]
*/
<?php
class ParentClass {
public function test() {
$this->privateMethod(); // 靜態綁定:永遠呼叫 ParentClass::privateMethod()
$this->publicMethod(); // 動態綁定:若子類覆寫則呼叫子類方法
}
private function privateMethod() { echo "Parent private\n"; }
public function publicMethod() { echo "Parent public\n"; }
}
class ChildClass extends ParentClass {
private function privateMethod() { echo "Child private\n"; } // 獨立方法,非覆寫
public function publicMethod() { echo "Child public\n"; } // 覆寫
}
$obj = new ChildClass();
$obj->test();
// 輸出:
// Parent private
// Child public
?>
private:編譯期綁定(靜態),不參與繼承,各類別擁有獨立同名方法。public/protected:執行期綁定(動態),支援多型。static:: 關鍵字解決 self:: 無法指向被呼叫類別的問題。| 模式 | 架構 | 優點 | 缺點 |
|---|---|---|---|
| mod_php (Apache 模組) | 內嵌於 Apache | 設定簡單、.htaccess 支援完整 | 記憶體佔用大、靜態檔案處理效率低 |
| CGI | 每請求啟動新進程 | 隔離性好 | 效能極差、幾乎淘汰 |
| FastCGI (PHP-FPM) | 常駐進程池 (C/S 架構) | 效能高、記憶體可控、支援平滑重啟 | 需額外設定、高併發下需調優進程數 |
生產環境主流組合: Nginx + PHP-FPM(高併發靜態/動態分離)或 Nginx 反向代理多台 Apache/PHP-FPM 叢集。
intUserCount、strUserName(型態前綴)userName、getUserList(首單字小寫,後續大寫)UserName、UserController(每單字首字母大寫,常用於類別名)// PHP 5.4+ 推薦
json_encode($data, JSON_UNESCAPED_UNICODE);
// 舊版相容
$tmp = array_map('urlencode', $data);
echo urldecode(json_encode($tmp));
header('Access-Control-Allow-Origin: *'); // 或指定域名
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');
透過 Hook 機制在 post_controller_constructor 階段攔截,根據 config.php 設定的 ssl_class_method / no_ssl_class_method 陣列決定是否重導至 HTTPS/HTTP。