My simple concern is being able to handle paths across OSs, mainly in the regard of back and forward slashes for directory separators.
I was using DIRECTORY_SEPARATOR
, however:
It's long to write
Paths may come from different sources, not necessarily controlled by you
I'm currently using:
function pth($path)
{
$runningOnWindows = (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN');
$slash = $runningOnWindows ? '\\' : '/';
$wrongSlash = $runningOnWindows ? '/' : '\\' ;
return (str_replace($wrongSlash, $slash, $path));
}
Just want to know that there is nothing existing in the language that I'm reinventing,
Is there already an inbuilt PHP functon to do this?
I'm aware of DIRECTORY_SEPARATOR,
However: 1. It's long to write
Laziness is never a reason for anything
$path = (DIRECTORY_SEPARATOR === '\\')
? str_replace('/', '\\', $subject)
: str_replace('\\', '/', $subject);
or
$path = str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, $path);
This will in one step replace "the right one" with itself, but that doesnt make any difference.
If you know for sure, that a path exists, you can use realpath()
$path = realpath($path);
However, that is not required at all, because every OS understands the forward slash /
as a valid directory separator (even windows).
You are missing the DIRECTORY_SEPARATOR
predefined constant.
If you're going to pass those paths to standard PHP functions, you actually don't need to fix paths, as far as I can tell. Basic functions like file_get_contents
or fopen
work perfectly fine with any kind of path you throw at them.
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