Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a platform independent directory separator in PHP?

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.

like image 628
retrodrone Avatar asked Jul 11 '11 17:07

retrodrone


2 Answers

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", "/");  
like image 57
genesis Avatar answered Oct 19 '22 05:10

genesis


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

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

like image 24
Maxim Mikhisor Avatar answered Oct 19 '22 04:10

Maxim Mikhisor