在 PHP 中讀取伺服器硬體資訊(如 MAC 地址)常用於授權驗證、設備識別等場景。本文提供一個支援 Windows 與 Linux 的封裝類別,自動偵測作業系統並呼叫對應指令解析結果。
ipconfig /all,解析「實體位址」。ifconfig -a 或 ip link,解析 ether 或 HWaddr 欄位。XX:XX:XX:XX:XX:XX 或 XX-XX-XX-XX-XX-XX)。<?php
/**
* 取得機器網卡 MAC 地址
* 支援 Windows / Linux 系統
*/
class MacAddInfo {
private $return_array = [];
public $mac_addr = '';
public function __construct($os_type = '') {
// 自動偵測作業系統
$os_type = $os_type ?: PHP_OS;
switch (strtolower($os_type)) {
case 'linux':
case 'unix':
case 'solaris':
case 'aix':
$this->forLinux();
break;
default:
$this->forWindows();
break;
}
$this->parseMacAddress();
}
/** Windows 環境呼叫 ipconfig */
private function forWindows() {
@exec("ipconfig /all", $this->return_array);
if (empty($this->return_array)) {
// 嘗試指定完整路徑
$windir = $_SERVER['WINDIR'] ?? 'C:\\Windows';
$paths = [
"$windir/system32/ipconfig.exe",
"$windir/system/ipconfig.exe"
];
foreach ($paths as $path) {
if (is_file($path)) {
@exec("$path /all", $this->return_array);
break;
}
}
}
}
/** Linux 環境呼叫 ifconfig */
private function forLinux() {
@exec("ifconfig -a", $this->return_array);
// 部分精簡系統無 ifconfig,可嘗試 ip link
if (empty($this->return_array)) {
@exec("ip link show", $this->return_array);
}
}
/** 從指令輸出中解析 MAC 地址 */
private function parseMacAddress() {
$pattern = '/([0-9a-f]{2}[:-]){5}[0-9a-f]{2}/i';
foreach ($this->return_array as $line) {
if (preg_match($pattern, $line, $matches)) {
$this->mac_addr = $matches[0];
break;
}
}
}
}
// 使用範例
$mac = new MacAddInfo();
echo "偵測到的 MAC 地址:" . ($mac->mac_addr ?: '未偵測到');
?>
ipconfig/ifconfig 權限(通常 CLI 模式無問題,Web 模式可能受限於 disable_functions 或使用者權限)。eth0、ens33)。若環境安裝 php-sysvsem、php-posix 擴展,亦可嘗試透過 /sys/class/net/*/address(Linux)讀取檔案方式獲取,避免執行外部指令,安全性更高。