PHP 的 ini_* 函數族提供了「無需重啟 PHP-FPM/Apache,即時讀寫配置」的能力。這在共享主機、無權限修改 php.ini、根據環境動態調整策略(如調試模式、上傳限制、錯誤報告)的場景極具價值。
ini_get(string $option): string|false
On/True/Yes → "1";Off/False/No → ""(空字符串)"8M"、"30")falsefunction safeInput(string $str): string {
// 檢查 magic_quotes_gpc 是否開啟(PHP 5.4+ 已移除,但舊項目可能仍需兼容)
if (ini_get('magic_quotes_gpc') === '1') {
return $str; // 已自動轉義
}
return addslashes($str); // 手動轉義
}
ini_set(string $option, string $value): string|false
PHP_INI_USER 或 PHP_INI_ALL 可修改)false| 場景 | 代碼 | 說明 |
|---|---|---|
| 開發環境開啟錯誤顯示 | ini_set('display_errors', '1'); | 生產環境嚴禁,配合 error_reporting(E_ALL) |
| 延長腳本執行時間 | ini_set('max_execution_time', '300'); | 替代 set_time_limit(300),適用於導出報表、批量處理 |
| 增加內存限制 | ini_set('memory_limit', '512M'); | 處理大圖片、大文件解析時臨時提升 |
| 動態擴展 include_path | ini_set('include_path', ini_get('include_path').PATH_SEPARATOR.'/custom/lib'); | 無權限改 php.ini 時引入私有庫 |
| 關閉危險函數(運行時補丁) | ini_set('disable_functions', 'exec,system,passthru'); | 僅影響當前腳本,無法恢復已禁用函數 |
[
'option_name' => [
'global_value' => 'php.ini 中的值',
'local_value' => '當前生效值(可能被 ini_set 修改)',
'access' => 7 // 位掩碼:1=PHP_INI_USER, 2=PHP_INI_PERDIR, 4=PHP_INI_SYSTEM
],
...
]
function auditIniSecurity(): array {
$all = ini_get_all();
$risky = [
'allow_url_fopen' => 'Off',
'allow_url_include' => 'Off',
'expose_php' => 'Off',
'register_globals' => 'Off',
'display_errors' => 'Off',
'log_errors' => 'On',
'open_basedir' => '非空',
'disable_functions' => '包含 exec,system 等',
];
$report = [];
foreach ($risky as $opt => $expected) {
$cur = $all[$opt]['local_value'] ?? '未設置';
$report[$opt] = [
'expected' => $expected,
'current' => $cur,
'status' => checkCompliance($opt, $cur, $expected) ? 'PASS' : 'FAIL'
];
}
return $report;
}
ini_restore(string $option): void
將指定選項恢復為 php.ini 定義的值(或啟動時的值)。常用於「臨時修改 → 執行敏感操作 → 恢復」模式:
// 臨時開啟錯誤顯示調試特定邏輯
ini_set('display_errors', '1');
try {
riskyOperation();
} finally {
ini_restore('display_errors'); // 確保恢復,防止影響後續邏輯
}
ini_get 適配環境,謹慎用 ini_set 改變全局行為。INI_DISPLAY_ERRORS = 'display_errors' 避免魔術字符串。ini_set 必須註明業務原因、影響範圍、恢復邏輯。