require_once dirname(__FILE__).DIRECTORY_SEPARATOR . './../../../wp-config.php';
require_once dirname(__FILE__).DIRECTORY_SEPARATOR.'inc/options.php';
The above code is from a plugin from the Wordpress.
I don't understand why half of it uses DIRECTORY_SEPARATOR
, but the other half uses "/"
?
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.
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 if DIRECTORY_SEPARATOR
is used
Using 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 as echo "<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 a DIRECTORY_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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With