手机浏览 RSS 2.0 订阅 膘叔的简单人生 , 腾讯云RDS购买 | 超便宜的Vultr , 注册 | 登陆
浏览模式: 标准 | 列表2011年01月13日的文章

Creating a absolute path from a relative URL

上午hihiyou问我,如何把“http://www.ss126.com/shop/../../bigimg/../bigimg/china-ef.com_200951117215473416.jpg”转换成实际路径的时候,我写了一个简单的方法:

PHP代码
  1. $url = 'http://www.ss126.com/shop/../../bigimg/../bigimg/china-ef.com_200951117215473416.jpg';  
  2.   
  3. $pathinfo = array(  
  4.     'path'=>'???',//相当于项目的根目录  
  5.     'url'=> 'http://www.ss126.com/'  
  6. );  
  7.   
  8. $url = realpath(str_replace($pathinfo['url'],$pathinfo['path'],$url));  //获取实际路径   
  9. //然后  
  10. if(strpos($url,$pathinfo['path'])!==false){//防止路径乱掉,或者进入其他目录   
  11.     $url = str_replace($pathinfo['path'],$pathinfo['info'],$url);  
  12. }else{  
  13.     $url = $pathinfo['url'];  
  14. }  

结果,他告诉我,不是本地程序。然后找了这样的代码 。。。

http://www.web-max.ca/PHP/misc_24.php
  1. <?php  
  2.   
  3.     $url = "http://www.goat.com/money/dave.html";  
  4.     $rel = "../images/cheese.jpg";  
  5.       
  6.     $com = InternetCombineURL($url,$rel);  
  7.       
  8. //  Returns http://www.goat.com/images/cheese.jpg  
  9.   
  10.     function InternetCombineUrl($absolute$relative) {  
  11.         $p = parse_url($relative);  
  12.         if($p["scheme"])return $relative;  
  13.           
  14.         extract(parse_url($absolute));  
  15.           
  16.         $path = dirname($path);   
  17.       
  18.         if($relative{0} == '/') {  
  19.             $cparts = array_filter(explode("/"$relative));  
  20.         }  
  21.         else {  
  22.             $aparts = array_filter(explode("/"$path));  
  23.             $rparts = array_filter(explode("/"$relative));  
  24.             $cparts = array_merge($aparts$rparts);  
  25.             foreach($cparts as $i => $part) {  
  26.                 if($part == '.') {  
  27.                     $cparts[$i] = null;  
  28.                 }  
  29.                 if($part == '..') {  
  30.                     $cparts[$i - 1] = null;  
  31.                     $cparts[$i] = null;  
  32.                 }  
  33.             }  
  34.             $cparts = array_filter($cparts);  
  35.         }  
  36.         $path = implode("/"$cparts);  
  37.         $url = "";  
  38.         if($scheme) {  
  39.             $url = "$scheme://";  
  40.         }  
  41.         if($user) {  
  42.             $url .= "$user";  
  43.             if($pass) {  
  44.                 $url .= ":$pass";  
  45.             }  
  46.             $url .= "@";  
  47.         }  
  48.         if($host) {  
  49.             $url .= "$host/";  
  50.         }  
  51.         $url .= $path;  
  52.         return $url;  
  53.     }  
  54.   
  55. ?>   

好吧。我承认,上面这个更方便一点。

Tags: absolute, relative