Windows 使用反斜線 \,Linux/macOS 使用正斜線 / 作為目錄分隔符。雖然 PHP 在 Windows 上也接受 /,但在字串操作、路徑解析、正則匹配等場景下,硬編碼分隔符會導致跨平台故障。
// Windows
define('DIRECTORY_SEPARATOR', '\\');
// Linux / macOS
define('DIRECTORY_SEPARATOR', '/');
<?php
// 僅在 Windows 正常,Linux 會產生雙重分隔符或路徑錯誤
$path = dirname(dirname(dirname(__FILE__))) . '\\';
$search = [$path, '\\'];
$replace = ['', '/'];
return str_replace($search, $replace, $this->tempfolder) . $this->filename_prefix . $public . '.jpg';
<?php
// 跨平台安全
$base = dirname(__FILE__) . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'wp-config.php';
require_once $base;
$inc = dirname(__FILE__) . DIRECTORY_SEPARATOR . 'inc' . DIRECTORY_SEPARATOR . 'options.php';
require_once $inc;
<?php
/**
* 將任意路徑統一為系統原生分隔符,並移除多餘分隔符
*/
function normalizePath(string $path): string
{
// 先統一為正斜線
$path = str_replace(['\\', '/'], DIRECTORY_SEPARATOR, $path);
// 移除重複分隔符(如 C:\\\\path -> C:\path)
$path = preg_replace('#' . preg_quote(DIRECTORY_SEPARATOR, '#') . '{2,}#', DIRECTORY_SEPARATOR, $path);
return $path;
}
// 使用範例
$path = normalizePath(__DIR__ . '/../config/' . 'database.php');
// Windows: C:\project\config\database.php
// Linux: /var/www/project/config/database.php
| 場景 | 推薦寫法 |
|---|---|
| 引入同目錄檔案 | require_once __DIR__ . DIRECTORY_SEPARATOR . 'config.php'; |
| 建立上層目錄路徑 | __DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'lib'; |
| 動態拼接模組路徑 | $modulePath = __DIR__ . DS . 'modules' . DS . $name . DS . 'boot.php';(const DS = DIRECTORY_SEPARATOR;) |
| 路徑字串替換/解析 | 統一用 DIRECTORY_SEPARATOR 作為搜尋/替換標記 |
/ 或 \,除非明確針對單一平台const DS = DIRECTORY_SEPARATOR; 簡化代碼realpath()、normalizePath() 處理相對/絕對路徑轉換