Converting relative URL to absolute

前端 未结 2 1215
野趣味
野趣味 2021-01-19 06:26

Let\'s say I have a URL of the document linking to another document (which can be both absolute or relative) and I need to have this link in absolute.

I made the sim

相关标签:
2条回答
  • 2021-01-19 06:46
    $uri = "..";
    $path = realpath($uri);
    $root = realpath($_SERVER["DOCUMENT_ROOT"]);
    
    if($path){
        $path = str_replace($root, "", $path);
        $path = $_SERVER["SERVER_NAME"] . $path;
        $protocol = "http";
        if(isset($_SERVER["HTTPS"])){
            $protocol .= "s";        
        }
        $path = "{$protocol}://$path";
        $path = str_replace("\\", "/", $path);
    }
    
    var_dump($path);
    

    There is probably a better/quicker way, but I just knocked this up...

    0 讨论(0)
  • 2021-01-19 06:56

    This function will resolve relative URLs to a given current page url in $pgurl without regex. It successfully resolves:

    /home.php?example types,

    same-dir nextpage.php types,

    ../...../.../parentdir types,

    full http://example.net urls,

    and shorthand //example.net urls

    //Current base URL (you can dynamically retrieve from $_SERVER)
    $pgurl = 'http://example.com/scripts/php/absurl.php';
    
    function absurl($url) {
     global $pgurl;
     if(strpos($url,'://')) return $url; //already absolute
     if(substr($url,0,2)=='//') return 'http:'.$url; //shorthand scheme
     if($url[0]=='/') return parse_url($pgurl,PHP_URL_SCHEME).'://'.parse_url($pgurl,PHP_URL_HOST).$url; //just add domain
     if(strpos($pgurl,'/',9)===false) $pgurl .= '/'; //add slash to domain if needed
     return substr($pgurl,0,strrpos($pgurl,'/')+1).$url; //for relative links, gets current directory and appends new filename
    }
    
    function nodots($path) { //Resolve dot dot slashes, no regex!
     $arr1 = explode('/',$path);
     $arr2 = array();
     foreach($arr1 as $seg) {
      switch($seg) {
       case '.':
        break;
       case '..':
        array_pop($arr2);
        break;
       case '...':
        array_pop($arr2); array_pop($arr2);
        break;
       case '....':
        array_pop($arr2); array_pop($arr2); array_pop($arr2);
        break;
       case '.....':
        array_pop($arr2); array_pop($arr2); array_pop($arr2); array_pop($arr2);
        break;
       default:
        $arr2[] = $seg;
      }
     }
     return implode('/',$arr2);
    }
    

    Usage Example:

    echo nodots(absurl('../index.html'));
    

    nodots() must be called after the URL is converted to absolute.

    The dots function is kind of redundant, but is readable, fast, doesn't use regex's, and will resolve 99% of typical urls (if you want to be 100% sure, just extend the switch block to support 6+ dots, although I've never seen that many dots in a URL).

    Hope this helps,

    0 讨论(0)
提交回复
热议问题