Вопрос

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");
Это было полезно?

Решение

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!

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top