Replace PHP's realpath()

前端 未结 6 1914
悲哀的现实
悲哀的现实 2020-12-05 01:21

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 s

6条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-05 01:53

    here is the modified code that supports UNC paths as well

    static public function truepath($path)
    {
        // whether $path is unix or not
        $unipath = strlen($path)==0 || $path{0}!='/';
        $unc = substr($path,0,2)=='\\\\'?true:false;
        // attempts to detect if path is relative in which case, add cwd
        if(strpos($path,':') === false && $unipath && !$unc){
            $path=getcwd().DIRECTORY_SEPARATOR.$path;
            if($path{0}=='/'){
                $unipath = false;
            }
        }
    
        // 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( function_exists('readlink') && file_exists($path) && linkinfo($path)>0 ){
            $path = readlink($path);
        }
        // put initial separator that could have been lost
        $path = !$unipath ? '/'.$path : $path;
        $path = $unc ? '\\\\'.$path : $path;
        return $path;
    }
    

提交回复
热议问题