替换PHP的realpath() [英] Replace PHP's realpath()

查看:81
本文介绍了替换PHP的realpath()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

显然,realpath的越野车非常多.在PHP 5.3.1中,它会导致随机崩溃. 在5.3.0及更低版本中,realpath随机失败并返回false(对于相同的字符串),而且它总是在realpath上失败-将相同的字符串两次/多次(当然,它第一次运行) ).

Apparently, realpath is very buggy. In PHP 5.3.1, it causes random crashes. In 5.3.0 and less, realpath randomly fails and returns false (for the same string of course), plus it always fails on realpath-ing the same string twice/more (and of course, it works the first time).

此外,它在早期的PHP版本中是如此的容易出错,以至于完全无法使用.嗯...已经不一样了,因为不一致.

Also, it is so buggy in earlier PHP versions, that it is completely unusable. Well...it already is, since it's not consistent.

无论如何,我有什么选择?也许是我自己改写的?这是明智的吗?

Anyhow, what options do I have? Maybe rewrite it by myself? Is this advisable?

推荐答案

感谢Sven Arduwie的代码( Pekka指出了)和一些修改,我构建了(希望)更好的实现:

Thanks to Sven Arduwie's code (pointed out by Pekka) and some modification, I've built a (hopefully) better implementation:

/**
 * This function is to replace PHP's extremely buggy realpath().
 * @param string The original path, can be relative etc.
 * @return string The resolved path, it might not exist.
 */
function truepath($path){
    // whether $path is unix or not
    $unipath=strlen($path)==0 || $path{0}!='/';
    // attempts to detect if path is relative in which case, add cwd
    if(strpos($path,':')===false && $unipath)
        $path=getcwd().DIRECTORY_SEPARATOR.$path;
    // resolve path parts (single dot, double dot and double delimiters)
    $path = str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, $path);
    $parts = array_filter(explode(DIRECTORY_SEPARATOR, $path), 'strlen');
    $absolutes = array();
    foreach ($parts as $part) {
        if ('.'  == $part) continue;
        if ('..' == $part) {
            array_pop($absolutes);
        } else {
            $absolutes[] = $part;
        }
    }
    $path=implode(DIRECTORY_SEPARATOR, $absolutes);
    // resolve any symlinks
    if(file_exists($path) && linkinfo($path)>0)$path=readlink($path);
    // put initial separator that could have been lost
    $path=!$unipath ? '/'.$path : $path;
    return $path;
}

NB:与PHP的realpath不同,此函数不会在出错时返回false;它会返回一条路径,以解决这些怪异问题.

NB: Unlike PHP's realpath, this function does not return false on error; it returns a path which is as far as it could to resolving these quirks.

注意2:显然有些人无法正确阅读. Truepath()在包含UNC和URL的网络资源上不起作用. 它仅适用于本地文件系统.

Note 2: Apparently some people can't read properly. Truepath() does not work on network resources including UNC and URLs. It works for the local file system only.

这篇关于替换PHP的realpath()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆