76

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.

3
  • possible duplicate of How do I properly split a PATH variable in PHP?
    – AJ.
    Commented Jul 11, 2011 at 17:46
  • 4
    Worth to mention: Windows works fine when using / as directory separator. There is usually no need to make it platform dependent. I don't know, what you mean with "the mix [..] confuses Windows"
    – KingCrunch
    Commented Jul 11, 2011 at 17:49
  • Thanks, @AJ. I missed that question.
    – retrodrone
    Commented Jul 11, 2011 at 17:51

2 Answers 2

135

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", "/"); 
12
  • 12
    however, both, Windows and Linux supports / so what's problem ?
    – genesis
    Commented Jul 11, 2011 at 17:52
  • 2
    The problem in my instance is I'm getting the first half of the path ($someDirectory) dynamically (from XULRunner) which uses '\' on Windows. PHP is giving '/' and Windows barfs at the slash combination.
    – retrodrone
    Commented Jul 11, 2011 at 17:53
  • 1
    Instead of "Windows" my server resturn "WINNT". Just in case.
    – spikey
    Commented Apr 17, 2013 at 10:23
  • 3
    Don't bother, this IS NOT necessary.
    – doublejosh
    Commented Jun 26, 2013 at 1:31
  • 4
    Not that it's critically important, but PATH_SEPARATOR is something else entirely (: on *nix, ; on Windows) and isn't a synonym of DIRECTORY_SEPARATOR.
    – icedwater
    Commented May 5, 2015 at 9:02
9
if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN')           
    define("SEPARATOR", "\\");
else 
    define("SEPARATOR", "/");

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.