PHP_OS_FAMILY === 'Linux' ? self::cpu() : null, 'memory' => self::memory(), ]; } private static function cpu(): ?array { $file = @fopen('/proc/stat', 'r'); if ($file === false) { return null; } $line = fgets($file); fclose($file); if ($line === false || !preg_match('/^cpu\h+(?:\d+\h+){7}\d+/', $line)) { return null; } $fields = array_map('intval', explode(' ', preg_replace('/\s+/', ' ', trim($line)))); // Exclude the guest fields. Linux already counts them in user and nice time. return ['total' => array_sum(array_slice($fields, 1, 8)), 'idle' => $fields[4] + $fields[5]]; } public static function memory(): ?string { if (PHP_OS_FAMILY !== 'Linux') { return null; } $info = @file_get_contents('/proc/meminfo'); if ($info === false || !preg_match('/^MemTotal:\s+(\d+) kB$/m', $info, $total) || !preg_match('/^MemAvailable:\s+(\d+) kB$/m', $info, $available) || (int) $total[1] === 0) { return null; } $capacity = (int) $total[1] * 1024; $used = max(0, $capacity - (int) $available[1] * 1024); return sprintf('%s / %s(%.1f%%)', self::bytes($used), self::bytes($capacity), 100 * $used / $capacity); } public static function bytes(int|float $bytes): string { $units = ['B', 'KiB', 'MiB', 'GiB', 'TiB']; $unit = 0; while ($bytes >= 1024 && $unit < count($units) - 1) { $bytes /= 1024; $unit++; } return ($unit === 0 ? (string) $bytes : number_format($bytes, 1)) . ' ' . $units[$unit]; } }