在開發系統管理工具或授權驗證機制時,常需要取得伺服器網卡的實體 MAC 位址。本文提供一個可直接部署的 PHP 類別 MacAddInfo,能自動偵測作業系統(Windows / Linux)並呼叫對應指令(ipconfig /all 或 ifconfig -a),最後以正則表達式萃取標準格式的 MAC 位址。
<?php
/**
* 取得機器網卡的物理 (MAC) 位址
* 目前支援 Windows / Linux 系統
*/
class MacAddInfo {
private $return_array = []; // 暫存指令回傳的原始字串
private $mac_addr; // 最終解析出的 MAC 位址
/**
* 建構子:依作業系統類型分派處理邏輯
* @param string $os_type PHP_OS 常數或自訂字串
*/
public function __construct($os_type) {
switch (strtolower($os_type)) {
case 'linux':
$this->forLinux();
break;
case 'solaris':
case 'unix':
case 'aix':
// 可依需求擴充其他 Unix-like 系統
break;
default:
$this->forWindows();
break;
}
// 從回傳資料中以正則比對 MAC 格式 (xx:xx:xx:xx:xx:xx 或 xx-xx-xx-xx-xx-xx)
$pattern = '/[0-9a-f]{2}[:-][0-9a-f]{2}[:-][0-9a-f]{2}[:-][0-9a-f]{2}[:-][0-9a-f]{2}[:-][0-9a-f]{2}/i';
foreach ($this->return_array as $line) {
if (preg_match($pattern, $line, $matches)) {
$this->mac_addr = $matches[0];
break;
}
}
}
/** 取得解析後的 MAC 位址 */
public function getMacAddr() {
return $this->mac_addr;
}
/** Windows 環境:呼叫 ipconfig /all */
private function forWindows() {
@exec('ipconfig /all', $this->return_array);
if (empty($this->return_array)) {
// 嘗試指定絕對路徑
$ipconfig = $_SERVER['WINDIR'] . '/system32/ipconfig.exe';
if (is_file($ipconfig)) {
@exec($ipconfig . ' /all', $this->return_array);
} else {
@exec($_SERVER['WINDIR'] . '/system/ipconfig.exe /all', $this->return_array);
}
}
}
/** Linux 環境:呼叫 ifconfig -a */
private function forLinux() {
@exec('ifconfig -a', $this->return_array);
}
}
// 使用範例
// $mac = new MacAddInfo(PHP_OS);
// echo $mac->getMacAddr();
?>
PHP_OS 常數自動判斷平台,免除手動切換。ipconfig 不在 PATH 中,會嘗試常見安裝路徑。: 或連字號 - 分隔,且不分大小寫。@exec 抑制錯誤訊息,避免洩露系統路徑;實際部署建議加入 escapeshellcmd 防禦指令注入。exec 函式執行權限(disable_functions 未禁用)。ifconfig,可改用 ip link show。break 並回傳陣列。