when to use DIRECTORY_SEPARATOR in PHP code?
All of the PHP IO functions will internally convert slashes to the appropriate character, so it's not a huge deal which method you use. Below are some things to consider.
It can look ugly and confusing when you print out your file paths and there is a mix of
\
and/
. This won't ever happen ifDIRECTORY_SEPARATOR
is usedUsing something such as
$generated_css = DIRECTORY_SEPARATOR.'minified.css';
will work all fine and dandy for file IO, but if a developer unknowingly references it in a URL such asecho "<link rel='stylesheet'
href='https://example.com$generated_css'>";
, a bug was just created. Did you catch it? While this will work on Windows, for everyone else a forward slash, instead of a backslash, will be in$generated_css
, resulting in the percent encoded, non-existant, URL https://example.com%5cgenerated_css! When using aDIRECTORY_SEPARATOR
you have to take special care to make sure your filepath variables never end up in a URL.And lastly, in the unlikely scenario your filepath is used by non-PHP code — for example, in a shell_exec call — you won't be able to mix slashes and will need to either construct the filepath with
DIRECTORY_SEPARATOR
or use realpath.
Because in different OS there is different directory separator. In Windows it's \
in Linux it's /
. DIRECTORY_SEPARATOR
is constant with that OS directory separator. Use it every time in paths.
In you code snippet we clearly see bad practice code. If framework/cms are widely used it doesn't mean that it's using best practice code.