PHP 提供多種內建常數與函式可偵測伺服器 OS,常用於跨平台路徑處理、指令執行、相依套件選擇等場景。本文整理最可靠的判斷方法與實務應用。
| 常數/函式 | Windows 值 | Linux/Unix 值 | 說明 |
|---|---|---|---|
PHP_OS | WINNT, WIN32 | Linux, FreeBSD, Darwin | 編譯時期 OS,最常用 |
PHP_OS_FAMILY (PHP 7.2+) | Windows | Linux, BSD, Darwin | 標準化家族名稱,推薦 |
php_uname('s') | Windows NT | Linux, FreeBSD, Darwin | 執行時期查詢,較詳細 |
DIRECTORY_SEPARATOR | \ | / | 路徑分隔符,間接判斷 |
PATH_SEPARATOR | ; | : | 環境變數分隔符 |
PHP_SHLIB_SUFFIX | dll | so | 動態庫副檔名 |
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';
}
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';
}
$basePath = '/var/www/html';
if (isWindows()) $basePath = 'C:\inetpub\wwwroot';
$fullPath = $basePath . DIRECTORY_SEPARATOR . 'uploads' . DIRECTORY_SEPARATOR . 'image.jpg';
// 自動產生正確分隔符
function listFiles(string $dir): array {
if (isWindows()) {
$cmd = 'dir /b ' . escapeshellarg($dir);
} else {
$cmd = 'ls -1 ' . escapeshellarg($dir);
}
exec($cmd, $output);
return $output;
}
$ext = isWindows() ? 'php_sqlsrv.dll' : 'php_pdo_pgsql.so';
if (!extension_loaded($ext)) {
dl($ext); // 僅 CLI / 特定 SAPI 可用
}
$tmpDir = sys_get_temp_dir(); // 自動回傳正確平台暫存目錄
$tmpFile = tempnam($tmpDir, 'myapp_');
PHP_OS 反映**容器 OS** (通常是 Linux),非宿主機 OS。/proc/version。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 程式碼。