整理 PHP 核心資訊函數,涵蓋環境變數、系統資源、版本資訊、配置讀寫等,附帶語法、說明與範例,適合開發除錯與環境檢測時快速查閱。
環境變數與執行資訊
| 函數 | 功能 | 範例 |
getenv(string $varname) | 獲取環境變數值 | getenv('REMOTE_ADDR') 取客戶端 IP |
get_current_user() | 取得腳本擁有者用戶名 | echo get_current_user(); |
getlastmod() | 取得腳本最後修改時間(Unix 時間戳) | date('Y-m-d H:i:s', getlastmod()) |
getrusage([int $who]) | 取得系統資源使用狀況(陣列) | $d=getrusage(); echo $d['ru_utime.tv_sec']; |
PHP 核心版本與配置資訊
| 函數 | 功能 | 備註 |
phpinfo([int $what]) | 輸出完整 PHP 配置資訊頁面 | 開發環境除錯必備,生產環境請刪除 |
phpversion() | 取得 PHP 版本字串 | 等同 PHP_VERSION 常數 |
ini_get(string $varname) | 取得單項配置值 | ini_get('memory_limit') |
ini_get_all() | 取得所有配置陣列 | 含全域/本地值、存取模式 |
ini_set(string $varname, string $newvalue) | 運行時修改配置 | 僅影響當前請求,部分配置不可改 |
get_cfg_var(string $option) | 取得 php.ini 原始配置值 | 不受 ini_set 影響 |
擴展與模組資訊
| 函數 | 功能 |
extension_loaded(string $name) | 檢查擴展是否已載入 |
get_loaded_extensions() | 返回所有已載入擴展名稱陣列 |
get_extension_funcs(string $module) | 返回指定模組提供的所有函數名稱 |
dl(string $library) | 動態載入 PHP 擴展(CLI/特定 SAPI 可用) |
路徑與包含檔案資訊
| 函數 | 功能 |
get_include_path() | 取得當前 include_path 設定 |
set_include_path(string $new_path) | 設定 include_path |
restore_include_path() | 還原 include_path 為 php.ini 設定 |
get_included_files() | 返回已 include/require 的檔案絕對路徑陣列 |
進程與資源限制
| 函數 | 功能 |
getmypid() | 取得當前 PHP 進程 ID |
getmyuid() / getmygid() | 取得腳本擁有者 UID/GID |
getmyinode() | 取得腳本檔案 inode 號 |
memory_get_usage() | 取得當前腳本佔用記憶體(位元組) |
set_time_limit(int $seconds) | 設定腳本最大執行秒數(0=無限制) |
魔術引號與安全相關(已棄用/移除)
PHP 5.4+ 已移除,僅供舊專案維護參考:
get_magic_quotes_gpc() / get_magic_quotes_runtime()
set_magic_quotes_runtime()
其他實用函數
| 函數 | 功能 |
php_uname() | 取得作業系統資訊字串 |
php_sapi_name() | 取得 SAPI 介面類型(apache2handler, cli, fpm-fcgi 等) |
php_ini_scanned_files() | 返回掃描目錄下的 .ini 檔案列表 |
php_logo_guid() / zend_logo_guid() | 取得 Logo 圖片 GUID(已棄用) |
zend_version() | 取得 Zend Engine 版本 |
assert_options() / assert() | 斷言配置與執行 |
version_compare(string $v1, string $v2 [, string $op]) | 版本號比較(支援運算符) |
最佳實踐建議
- 資訊洩露風險:生產環境嚴禁公開
phpinfo()、get_included_files() 等敏感輸出
- 配置讀取優先用
ini_get(),需原始值用 get_cfg_var()
- 跨平台路徑處理用
DIRECTORY_SEPARATOR、PATH_SEPARATOR 常數
- 記憶體監控:長時間運行腳本定期檢查
memory_get_usage() 防洩漏