phpinspectionsea
phpinspectionsea copied to clipboard
Suggests usage of slash instead of backslash in path related functions
Unix and Windows could uses / as directory separator. Windows could too uses \, but it is invalid for Unix distros. And I have spent 4 hours do identify an issue caused for that.
Basically, any path related function (eg. is_dir(), is_file(), file_exists(), so on) should be inspected if inner strings uses \ to separate folders. I don't think that DIRECTORY_SEPARATOR is valid for all cases once that it could turn code very long -- although it could avoid this kind of issue.
Example:
if (is_dir(getcwd() . '\\vendor')) {
// Warning: using backslash will turn this path invalid for Unix systems.
// Quickfix: replace \\ to /
}
The example above could be simplified to use DIRECTORY_SEPARATOR (that maybe could be a new inspection or could be applied as quickfix for that case). But the case below will turn the code that to understand:
if (is_file('vendor\\laravel\\framework\\src\\Illuminate\\Support\\Collection.php')) {
// Warning: using backslash will turn this path invalid for Unix systems.
// Quickfix: replace \\ to /
}
Oh, that was obviously annoying. Will add as a new inspection.
The use of DIRECTORY_SEPARATOR can actually break the code in some edge cases.
For example, if you are running a CygWin environment under Windows, you're running a simulation of a POSIX environment (which should use /), but as you are using a Windows version of PHP, DIRECTORY_SEPARATOR returns \. So, depending on how you combine these, you'll end up with broken strings.
Also, some people develop on Unix environments (using /) and turn a relative filesystem path (like assets/images/logo.png) into a URL (=> https://example.com/assets/images/logo.png). When this relative path was built using DIRECTORY_SEPARATOR and the code is run on a Windows machine, it will break, as it will generate a URL similar to this: https://example.com\assets\images\logo.png.
That's why I recommend only using / when building path strings.