如何通过PHP跨平台获取服务器CPU型号(无需额外依赖)
跨平台PHP获取CPU型号的纯PHP方案
核心思路
通过检测当前操作系统类型,执行对应系统的原生命令读取CPU型号,全程依赖PHP内置函数,无需额外安装组件。
分平台实现方案
- Linux系统:优先读取
/proc/cpuinfo文件(无命令执行权限时可用),若文件不可读则尝试lscpu命令提取型号。 - Windows系统:使用
wmic cpu get name命令获取CPU名称。 - macOS系统:补充支持
sysctl命令读取CPU品牌信息。
完整示例代码
<?php $cpuModel = '无法获取CPU型号'; // 获取操作系统类型 $osType = strtolower(php_uname('s')); // 处理Linux系统 if (str_contains($osType, 'linux')) { // 优先尝试读取/proc/cpuinfo if (file_exists('/proc/cpuinfo') && is_readable('/proc/cpuinfo')) { $cpuContent = file_get_contents('/proc/cpuinfo'); if (preg_match('/model name\s*: (.*)/i', $cpuContent, $matches)) { $cpuModel = trim($matches[1]); } } else { // 退而使用lscpu命令 $output = []; exec('lscpu | grep -i "model name"', $output); if (!empty($output[0])) { $cpuModel = trim(preg_replace('/model name\s*: /i', '', $output[0])); } } } // 处理Windows系统 elseif (str_contains($osType, 'windows')) { $output = []; exec('wmic cpu get name /value', $output); foreach ($output as $line) { $line = trim($line); if (str_starts_with($line, 'Name=')) { $cpuModel = trim(substr($line, 5)); break; } } } // 处理macOS系统 elseif (str_contains($osType, 'darwin')) { $output = []; exec('sysctl -n machdep.cpu.brand_string', $output); if (!empty($output[0])) { $cpuModel = trim($output[0]); } } echo $cpuModel; ?>
注意事项
- 需确保PHP的
exec函数未被禁用(检查php.ini中的disable_functions配置)。 - 部分共享主机可能限制文件读取或命令执行权限,这种情况下可能无法获取信息。
- 正则匹配使用不区分大小写模式,适配不同系统的输出格式差异。
内容的提问来源于stack exchange,提问作者jspit
相关产品推荐
相关产品推荐

