萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 判斷伺服器作業系統類型:跨平台相容性處理指南

核心方法:預定義常數 PHP_OS / PHP_OS_FAMILY

PHP 提供編譯時期確定的常數,無需執行額外函數,效能最佳:

<?php
// PHP 7.2+ 推薦:標準化家族名稱
echo PHP_OS_FAMILY; // 'Windows', 'Linux', 'Darwin', 'BSD', 'Solaris', etc.

// 所有版本通用:原始字串
echo PHP_OS; // 'WINNT', 'Linux', 'Darwin', 'FreeBSD', 'SunOS'...

常見判斷邏輯

<?php
function getOsFamily(): string {
    // 現代寫法(PHP 7.2+)
    if (defined('PHP_OS_FAMILY')) {
        return PHP_OS_FAMILY;
    }
    // 兼容舊版:解析 PHP_OS
    $os = strtolower(PHP_OS);
    if (str_starts_with($os, 'win')) return 'Windows';
    if (str_starts_with($os, 'linux')) return 'Linux';
    if (str_starts_with($os, 'darwin')) return 'Darwin';
    if (str_starts_with($os, 'freebsd')) return 'BSD';
    if (str_starts_with($os, 'sunos')) return 'Solaris';
    return 'Unknown';
}

// 使用範例
$os = getOsFamily();
match ($os) {
    'Windows' => $pathSeparator = '\\',
    'Linux', 'Darwin', 'BSD' => $pathSeparator = '/',
    default => $pathSeparator = DIRECTORY_SEPARATOR, // 內建常數自動適配
};
echo "路徑分隔符: $pathSeparator\n";

其他輔助常數與函數

常數/函數值範例用途
DIRECTORY_SEPARATOR\ (Win) / / (*nix)路徑分隔符,建構跨平台路徑必用
PATH_SEPARATOR; (Win) / : (*nix)環境變數 PATH 分隔符
PHP_SHLIB_SUFFIXdll / so動態庫副檔名
php_uname('s')Windows NT / Linux / Darwin運行時核心名稱(非編譯目標)
php_uname('r')10.0.19045 / 5.15.0-91-generic核心版本
php_uname('a')完整資訊字串診斷/日誌用

實戰場景

1. 跨平台路徑構建

<?php
$base = '/var/www/app';
$path = $base . DIRECTORY_SEPARATOR . 'storage' . DIRECTORY_SEPARATOR . 'logs';
// Windows: \var\www\app\storage\logs
// Linux:   /var/www/app/storage/logs

2. 執行系統命令區分

<?php
$os = PHP_OS_FAMILY ?? strtoupper(substr(PHP_OS, 0, 3));
$cmd = match ($os) {
    'Windows' => 'dir /b ' . escapeshellarg($dir),
    default   => 'ls -la ' . escapeshellarg($dir),
};
exec($cmd, $output);

3. 條件載入擴展/配置

<?php
if (PHP_OS_FAMILY === 'Windows') {
    // Windows 專用:COM、WinCache、SQLSRV
    if (!extension_loaded('com_dotnet')) dl('php_com_dotnet.dll');
} else {
    // *nix 專用:pcntl、posix、inotify、redis cluster
    if (!extension_loaded('pcntl')) dl('pcntl.so');
}

4. 檔案權限/鎖機制差異

<?php
$lockFile = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'myapp.lock';
$fp = fopen($lockFile, 'c+');
if (PHP_OS_FAMILY === 'Windows') {
    // Windows 強制鎖定
    flock($fp, LOCK_EX | LOCK_NB) or die('Another instance running');
} else {
    // *nix 建議用 flock (建議鎖) 或 fcntl
    flock($fp, LOCK_EX | LOCK_NB) or die('Another instance running');
}

容器化環境注意事項

  • Docker 容器中 PHP_OS 反映建構映像的宿主核心(通常為 Linux),即使運行在 Windows/macOS 主機上。
  • 若需檢測「宿主 OS」,需掛載 /proc/version 或讀取環境變數(如 HOST_OS)。
  • Kubernetes 節點選擇器 kubernetes.io/os 更可靠。

完整封裝工具類

<?php
class Platform {
    public static function isWindows(): bool {
        return (PHP_OS_FAMILY ?? 'WIN') === 'Windows' || stripos(PHP_OS, 'WIN') === 0;
    }
    public static function isLinux(): bool {
        return (PHP_OS_FAMILY ?? '') === 'Linux' || stripos(PHP_OS, 'LINUX') === 0;
    }
    public static function isMac(): bool {
        return (PHP_OS_FAMILY ?? '') === 'Darwin' || stripos(PHP_OS, 'DARWIN') === 0;
    }
    public static function family(): string {
        return PHP_OS_FAMILY ?? (self::isWindows() ? 'Windows' : (self::isMac() ? 'Darwin' : 'Linux'));
    }
    public static function pathSep(): string { return DIRECTORY_SEPARATOR; }
    public static function pathJoin(string ...$parts): string {
        return implode(DIRECTORY_SEPARATOR, array_filter($parts));
    }
    public static function normalizePath(string $path): string {
        return str_replace(['/', '\\'], DIRECTORY_SEPARATOR, $path);
    }
}

// 使用
$logDir = Platform::pathJoin(sys_get_temp_dir(), 'myapp', 'logs');
if (Platform::isWindows()) {
    // Windows 特有邏輯
}

最佳實踐:優先使用 PHP_OS_FAMILY(PHP 7.2+)、DIRECTORY_SEPARATOR、PATH_SEPARATOR 等內建常數;避免解析 php_uname() 字串;容器環境下信任映像標籤而非運行時檢測。

copyright © 萬盛學電腦網 all rights reserved