How to get a platform independent directory separator in PHP?

I am building a path string in PHP. I need it to work on different platforms (e.g. Linux, Windows, OS X). I'm doing it:

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

Suppose that $someDirectory and $someFile formatted correctly at runtime on different platforms. This works great on Linux and OS X, but not on Windows. The problem is with 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: To be clear, the resulting string

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

on Windows. Obviously, a slash combination is confusing Windows.

+49
directory php filepath
Jul 11 2018-11-17T00:
source share
2 answers

Try this one

DIRECTORY_SEPARATOR

 $patch = $somePath. DIRECTORY_SEPARATOR .$someFile 

or you can define your

 PHP_OS == "Windows" || PHP_OS == "WINNT" ? define("SEPARATOR", "\\") : define("SEPARATOR", "/"); 
+99
Jul 11 2018-11-11T00:
source share
 if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') define("SEPARATOR", "\\"); else define("SEPARATOR", "/"); 

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

+7
Nov 26 '13 at
source share



All Articles