将url(包含点)转换为相对

时间:2015-01-30 16:51:56

标签: php url path sanitize

是否有任何PHP函数,以清理链接+路径? 即。

http://example.com/fold1/fold2/fold3/../../././MyFile.HTML
to
http://example.com/fold1/MyFile.HTML

所以,我想删除点,但保持合适的(相对)正确的路径。

2 个答案:

答案 0 :(得分:0)

我到目前为止找到的是:

echo ConvertDotedPathToNormalUrl('http://example.com/directory/.././pageee.html');

代码:

function ConvertDotedPathToNormalUrl($url){
    $firstType = '/(.*)\/((?:(?!\.\.).)+)\/\.\.\//si';
    preg_match($firstType,$url,$result); 
    if (!empty($result[2])){
        $url = str_replace('/'.$result[2].'/..','',$url);
        if ( strstr($url,'../')){$url= ConvertDotedPathToNormalUrl($url);} 
    }
    $url = str_replace('/./','/',$url); $url = str_replace('://','|||',$url);$url = str_replace('//','/',$url);$url = str_replace('|||','://',$url);
    return $url;
}

P.S。但不是,它会转换

答案 1 :(得分:0)

你可以
1)使用parse_url(..)获取$ path 2)获取$ webroot = $ _SERVER [' DOCUMENT_ROOT'];
3)获取$ zrealpath = realpath($ webroot。$ path);

<?php
  define ('CRLF', "<br />\n");
  $url = 'http://example.com/fold1/fold2/fold3/../../././MyFile.HTML';
  $parsed = parse_url($url);
  echo '---- vardump($parsed):', CRLF; // for education
  zvardump($parsed);
  $webroot = $_SERVER['DOCUMENT_ROOT'];
  echo 'webroot = ', $webroot, CRLF;
  $path = $parsed['path'];
  echo 'path = ', $path, CRLF;
  $zrealpath = realpath($webroot . $path);
  echo 'realpath = ', $zrealpath, CRLF;

function zvardump($var1) {
  ob_start();
  echo "<pre style=\"margin:0;\">\n";
  var_dump($var1);
  echo "</pre>\n";
  $zoutput = ob_get_contents();
  ob_end_clean();
  echo str_replace("=>\n  ", " => ", $zoutput);
  }
?>