How to get a platform independent directory separator in PHP?

PhpDirectoryFilepath

Php Problem Overview


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.

Php Solutions


Solution 1 - Php

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", "/"); 

Solution 2 - Php

if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN')           
    define("SEPARATOR", "\\");
else 
    define("SEPARATOR", "/");

http://php.net/manual/en/function.php-uname.php

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionretrodroneView Question on Stackoverflow
Solution 1 - PhpgenesisView Answer on Stackoverflow
Solution 2 - PhpMaxim MikhisorView Answer on Stackoverflow