when to use DIRECTORY_SEPARATOR in PHP code?

前端 未结 3 1104
情话喂你
情话喂你 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 "<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.

    0 讨论(0)
  • 2020-12-16 12:00

    Do not use your own folder separators. Always use DIRECTORY_SEPARATOR, because:

    1. In some special cases you really need the correct path delimiter
    2. The OS might handle it correctly, but many 3rd party applications can't and might fail!
    3. Some operating systems do not use / or \ as separators but something different

    Don't forget: Use the constant only on the remote system - don't use it for URIs or anything else that you want to send to the client (except you really need it, like a "remote browser").

    0 讨论(0)
  • 2020-12-16 12:21

    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.

    0 讨论(0)
提交回复
热议问题