本文內容與 ID 148074 高度重複,此處提供精簡版核心代碼與關鍵差異說明。完整類實現請參考前述文章。
<?php
/** 獲取 sysctl 參數 */
function sysctl(string $key): ?string {
$out = @shell_exec('sysctl -n ' . escapeshellarg($key));
return $out ? trim($out) : null;
}
/** CPU 信息 */
function getCpu(): array {
return [
'cores' => (int)(sysctl('hw.ncpu') ?? 0),
'model' => sysctl('hw.model') ?? 'Unknown',
];
}
/** 負載 */
function getLoad(): array {
$load = sysctl('vm.loadavg');
$load = trim($load ?? '', '{}');
$parts = array_map('floatval', explode(' ', $load));
return ['1min'=>$parts[0]??0, '5min'=>$parts[1]??0, '15min'=>$parts[2]??0];
}
/** 運行時間 */
function getUptime(): array {
$bt = sysctl('kern.boottime');
if (preg_match('/sec\s*=\s*(\d+)/', $bt ?? '', $m)) {
$boot = (int)$m[1];
$up = time() - $boot;
return ['seconds'=>$up, 'human'=>sprintf('%d天 %d時 %d分', $up/86400, ($up%86400)/3600, ($up%3600)/60), 'boot_time'=>$boot];
}
return ['error'=>'解析失敗'];
}
/** 內存 */
function getMemory(): array {
$total = round((sysctl('hw.physmem') ?? 0) / 1024 / 1024, 2); // MB
$vmstat = @shell_exec('vmstat');
$free = 0;
if ($vmstat) {
$lines = explode("\n", trim($vmstat));
if (isset($lines[2])) {
$free = round((preg_split('/\s+/', $lines[2])[4] ?? 0) / 1024, 2);
}
}
$used = $total - $free;
return ['total'=>$total, 'free'=>$free, 'used'=>$used, 'percent'=>$total?round($used/$total*100,2):0];
}
/** Swap */
function getSwap(): array {
$swap = @shell_exec('swapinfo -k');
$arr = ['total'=>0,'used'=>0,'free'=>0,'percent'=>0];
if ($swap) {
$lines = explode("\n", trim($swap));
if (isset($lines[1])) {
$f = preg_split('/\s+/', $lines[1]);
$arr['total'] = round($f[0]/1024,2);
$arr['used'] = round($f[1]/1024,2);
$arr['free'] = round($f[2]/1024,2);
$arr['percent'] = $arr['total']?round($arr['used']/$arr['total']*100,2):0;
}
}
return $arr;
}
?>
| 指標 | Linux (/proc) | FreeBSD (sysctl/命令) |
|---|---|---|
| CPU 核心 | /proc/cpuinfo 行計數 | sysctl hw.ncpu |
| 負載格式 | 空格分隔純數字 | 大括號包裹 { 1.23 0.98 0.76 } |
| 啟動時間 | /proc/uptime 秒數 | sysctl kern.boottime (Unix 時間戳) |
| 空閒內存 | /proc/meminfo MemFree | vmstat 第 3 行第 5 欄 |
| Swap 信息 | /proc/meminfo | swapinfo -k |
disable_functions 未禁用 shell_execsafe_mode_exec_dir 包含 /usr/sbin (sysctl/vmstat/swapinfo 位置)