Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: a good way to universalize paths across OSs (slash directions)

My simple concern is being able to handle paths across OSs, mainly in the regard of back and forward slashes for directory separators.

I was using DIRECTORY_SEPARATOR, however:

  1. It's long to write

  2. Paths may come from different sources, not necessarily controlled by you

I'm currently using:

    function pth($path)
    {
        $runningOnWindows = (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN');
        $slash = $runningOnWindows ? '\\' : '/';
        $wrongSlash = $runningOnWindows ? '/' : '\\' ;
        return (str_replace($wrongSlash, $slash, $path));
    }

Just want to know that there is nothing existing in the language that I'm reinventing,

Is there already an inbuilt PHP functon to do this?

like image 865
shealtiel Avatar asked Apr 12 '11 23:04

shealtiel


3 Answers

I'm aware of DIRECTORY_SEPARATOR,

However: 1. It's long to write

Laziness is never a reason for anything

$path = (DIRECTORY_SEPARATOR === '\\')
      ? str_replace('/', '\\', $subject)
      : str_replace('\\', '/', $subject);

or

$path = str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, $path);

This will in one step replace "the right one" with itself, but that doesnt make any difference.

If you know for sure, that a path exists, you can use realpath()

$path = realpath($path);

However, that is not required at all, because every OS understands the forward slash / as a valid directory separator (even windows).

like image 64
KingCrunch Avatar answered Nov 12 '22 20:11

KingCrunch


You are missing the DIRECTORY_SEPARATOR predefined constant.

like image 45
Jon Avatar answered Nov 12 '22 21:11

Jon


If you're going to pass those paths to standard PHP functions, you actually don't need to fix paths, as far as I can tell. Basic functions like file_get_contents or fopen work perfectly fine with any kind of path you throw at them.

like image 26
Ludovic Chabant Avatar answered Nov 12 '22 20:11

Ludovic Chabant