PHP: a good way to universalize paths across OSs (slash directions)
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.
static function fx_slsh($path) {
$path = str_replace(['/','\\'], DIRECTORY_SEPARATOR, $path);
return substr($path, -1) == DIRECTORY_SEPARATOR ? $path : $path . DIRECTORY_SEPARATOR;
}
this one will also ensure there is a trailing slash
You can simply change everything to forward slashes /
. Get rid of back slashes \
entirely. Forward slashes work on all OS's, including Windows.
精彩评论