1

Problem:

Both, dirname() and realpath() returns a path with the correct slashes depending what OS you are running the script.

I want to create a path in a portable way (using PHP API) so I don't have to worried about \ or / slashes.

realpath() returns FALSE if the path doesn't exist. So, it's not an option to do:

define("MY_PATH", realpath(__DIR__."/myNewDirToCreate");

In other different case, dirname() will not be an option for:

define("MY_FILE", "I/should/use/an/abstract/path/definition.file");

because it will return the parten directory, not the path to the file. I could handle the problem by myself, using either regex or string replace. But PHP is a cross-platform environment and for sure I'm missing some function in the extensive PHP documentation.

Question:

  • How do I create a path no matter what OS is the script running on using PHP API, if possible? e.g. path("no/matter/what/os/are/you/running/this.file\or\what\slashes\you\are\using");
Sebastian
  • 4,770
  • 4
  • 42
  • 43
  • 2
    You should not care about forward and backward slashes, they will both work. All you have to do is to use dirname() to get the base path, then, from there, just use forward slash everywhere and it will be just fine, i promise :) – Twisted1919 Jun 13 '13 at 21:23
  • @Twisted1919 you were right. An error in my code misslead me that the error was the mixin of slashes. – Sebastian Jun 13 '13 at 21:33

1 Answers1

4

There is a constant available, it is called DIRECTORY_SEPARATOR.

$path_to_file = $directory . DIRECTORY_SEPARATOR . $file

It‘s documented here: http://php.net/manual/en/dir.constants.php#constant.directory-separator

Be advised that PHP handles this internally, so on Windows you may get a forward slash, but they will work just fine inside PHP!

Palec
  • 12,743
  • 8
  • 69
  • 138
The Surrican
  • 29,118
  • 24
  • 122
  • 168