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

FreeBSD 系統參數探測:PHP 獲取 CPU、內存、負載、運行時間

     編輯:PHP 相關知識

說明

本文內容與 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 版關鍵差異

指標Linux (/proc)FreeBSD (sysctl/命令)
CPU 核心/proc/cpuinfo 行計數sysctl hw.ncpu
負載格式空格分隔純數字大括號包裹 { 1.23 0.98 0.76 }
啟動時間/proc/uptime 秒數sysctl kern.boottime (Unix 時間戳)
空閒內存/proc/meminfo MemFreevmstat 第 3 行第 5 欄
Swap 信息/proc/meminfoswapinfo -k

部署檢查清單

  • PHP disable_functions 未禁用 shell_exec
  • safe_mode_exec_dir 包含 /usr/sbin (sysctl/vmstat/swapinfo 位置)
  • 運行用戶有執行上述命令權限(通常需 wheel 組或 sudoers 配置)
  • 命令輸出格式可能因 FreeBSD 版本 (12/13/14) 微異,建議加正則容錯
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved