The PHP DIRECTORY_SEPARATOR
constant is used as a placeholder for the directory separator symbol for the operating system that runs the PHP script.
In macOS and other UNIX-based OS, the directory separator is a slash (path/to/file
)
In Windows, both slash and backslash symbols can be used as the directory separator (path/to/file
or path\to\file
)
Because these three are the only popular operating systems used worldwide, you don’t really need the DIRECTORY_SEPARATOR
constant when defining a file location.
You can replace the DIRECTORY_SEPARATOR
constant with the forward slash symbol and it should run without issues in Windows, macOS, and Linux:
// Both are the same
$file = "path" . DIRECTORY_SEPARATOR . "to" . DIRECTORY_SEPARATOR . "file";
$file = 'path/to/file';
Even if a different operating system may be used in the future, most likely it will also adhere to the standard of using a slash as the directory separator symbol.
But if you feel that you need to use the DIRECTORY_SEPARATOR
constant, then the best way to construct a path is to use the join()
function.
Here’s an example of constructing a path with the DIRECTORY_SEPARATOR
constant:
<?php
$path = join(DIRECTORY_SEPARATOR, array("path", "to", "file"));
print $path;
// UNIX output: path/to/file
// Windows output: path\to\file
Using the join()
function will save you from having to type DIRECTORY_SEPARATOR
many times.
The DIRECTORY_SEPARATOR
constant grants you a future-proof syntax if somehow the directory separator symbol gets changed (although it’s not likely going to happen)