when to use DIRECTORY_SEPARATOR in PHP code?

前端 未结 3 1106
情话喂你
情话喂你 2020-12-16 11:14

Look at the PHP code:

require_once dirname(__FILE__).DIRECTORY_SEPARATOR . \'./../../../wp-config.php\';
require_once dirname(__FILE__).DIRECTORY_SEPARATOR.\'         


        
3条回答
  •  春和景丽
    2020-12-16 11:58

    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 "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.

提交回复
热议问题