shealtiel
shealtiel

Reputation: 8388

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?

Upvotes: 12

Views: 18110

Answers (5)

RedDragonWebDesign
RedDragonWebDesign

Reputation: 2581

You can simply change everything to forward slashes /. Get rid of back slashes \ entirely. Forward slashes work on all OS's, including Windows.

Upvotes: 1

smclaughlin
smclaughlin

Reputation: 11

  static function fx_slsh($path) {
    $path = str_replace(['/','\\'], DIRECTORY_SEPARATOR, $path);
    return substr($path, -1) == DIRECTORY_SEPARATOR ? $path : $path . DIRECTORY_SEPARATOR;
  }

this one will also ensure there is a trailing slash

Upvotes: 0

KingCrunch
KingCrunch

Reputation: 132061

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).

Upvotes: 40

Ludovic Chabant
Ludovic Chabant

Reputation: 1513

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.

Upvotes: 1

Jon
Jon

Reputation: 437784

You are missing the DIRECTORY_SEPARATOR predefined constant.

Upvotes: 6

Related Questions