How to get a platform independent directory separator in PHP?

retrodrone picture retrodrone · Jul 11, 2011 · Viewed 57.2k times · Source

I'm building a path string in PHP. I need it to work across platforms (i.e., Linux, Windows, OS X). I'm doing this:

$path = $someDirectory.'/'.$someFile;

Assume $someDirectory and $someFile are formatted correctly at run-time on the various platforms. This works beautifully on Linux and OS X, but not on Windows. The issue is the / character, which I thought would work for Windows.

Is there a PHP function or some other trick to switch this to \ at runtime on Windows?

EDIT: Just to be clear, the resultant string is

c:\Program Files (x86)\Sitefusion\Sitefusion.org\Defaults\pref/user.preferences

on Windows. Obviously the mix of slashes confuses Windows.

Answer

genesis picture genesis · Jul 11, 2011

Try this one

DIRECTORY_SEPARATOR

$patch = $somePath. DIRECTORY_SEPARATOR .$someFile

or you can define yours

PHP_OS == "Windows" ||
    PHP_OS == "WINNT" ? define("SEPARATOR", "\\") : define("SEPARATOR", "/");