首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

PHP 判斷伺服器作業系統類型

     編輯:PHP 相關知識

PHP 提供多種內建常數與函式可偵測伺服器 OS,常用於跨平台路徑處理、指令執行、相依套件選擇等場景。本文整理最可靠的判斷方法與實務應用。

核心判斷依據

常數/函式Windows 值Linux/Unix 值說明
PHP_OSWINNT, WIN32Linux, FreeBSD, Darwin編譯時期 OS,最常用
PHP_OS_FAMILY (PHP 7.2+)WindowsLinux, BSD, Darwin標準化家族名稱,推薦
php_uname('s')Windows NTLinux, FreeBSD, Darwin執行時期查詢,較詳細
DIRECTORY_SEPARATOR\/路徑分隔符,間接判斷
PATH_SEPARATOR;:環境變數分隔符
PHP_SHLIB_SUFFIXdllso動態庫副檔名

推薦寫法 (PHP 7.2+)

function getServerOS(): string {
    // PHP_OS_FAMILY 回傳 'Windows', 'Linux', 'Darwin', 'BSD', 'Solaris' 等
    return PHP_OS_FAMILY;
}

// 簡單分支
if (PHP_OS_FAMILY === 'Windows') {
    // Windows 邏輯
    $path = 'C:\www\app';
    $cmd  = 'dir';
} else {
    // Unix-like 邏輯
    $path = '/var/www/app';
    $cmd  = 'ls -la';
}

相容舊版本寫法 (PHP 5.3+)

function isWindows(): bool {
    return strtolower(substr(PHP_OS, 0, 3)) === 'win';
    // 或: return strtoupper(substr(PHP_OS, 0, 3)) === 'WIN';
}

function getOSFamily(): string {
    if (isWindows()) return 'Windows';
    $os = php_uname('s');
    if (strpos($os, 'Linux') !== false) return 'Linux';
    if (strpos($os, 'Darwin') !== false) return 'macOS';
    if (strpos($os, 'BSD') !== false) return 'BSD';
    return 'Unix';
}

實務應用範例

1. 跨平台路徑處理

$basePath = '/var/www/html';
if (isWindows()) $basePath = 'C:\inetpub\wwwroot';

$fullPath = $basePath . DIRECTORY_SEPARATOR . 'uploads' . DIRECTORY_SEPARATOR . 'image.jpg';
// 自動產生正確分隔符

2. 執行系統指令

function listFiles(string $dir): array {
    if (isWindows()) {
        $cmd = 'dir /b ' . escapeshellarg($dir);
    } else {
        $cmd = 'ls -1 ' . escapeshellarg($dir);
    }
    exec($cmd, $output);
    return $output;
}

3. 載入平台相依擴充

$ext = isWindows() ? 'php_sqlsrv.dll' : 'php_pdo_pgsql.so';
if (!extension_loaded($ext)) {
    dl($ext); // 僅 CLI / 特定 SAPI 可用
}

4. 臨時檔案路徑

$tmpDir = sys_get_temp_dir(); // 自動回傳正確平台暫存目錄
$tmpFile = tempnam($tmpDir, 'myapp_');

容器化環境注意事項

  • Docker 容器中 PHP_OS 反映**容器 OS** (通常是 Linux),非宿主機 OS。
  • 若需判斷宿主機,需透過環境變數傳入或掛載 /proc/version。
  • Windows Containers (LTSC) 回傳 Windows,行為一致。

完整偵測工具類

class Platform {
    public static function isWindows(): bool {
        return PHP_OS_FAMILY === 'Windows' ?? (strtolower(substr(PHP_OS, 0, 3)) === 'win');
    }
    public static function isLinux(): bool {
        return PHP_OS_FAMILY === 'Linux' ?? (strpos(php_uname('s'), 'Linux') !== false);
    }
    public static function isMac(): bool {
        return PHP_OS_FAMILY === 'Darwin' ?? (strpos(php_uname('s'), 'Darwin') !== false);
    }
    public static function getShell(): string {
        return self::isWindows() ? 'cmd.exe' : '/bin/sh';
    }
    public static function getLineEnding(): string {
        return self::isWindows() ? "\r\n" : "\n";
    }
}

善用 PHP_OS_FAMILY 與 DIRECTORY_SEPARATOR 等內建常數,能寫出真正跨平台、零硬編碼的 PHP 程式碼。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved