Jump to content

convert relative path to url


The Little Guy

Recommended Posts

Any thoughts on this function? Basically what it does is take the current users location ($location) and a relative path ($link) and convert it to a valid URL. I do know that this does work on my example, but does anyone have any suggestions on this?

 

<?php
$location = "http://mysite.com/pages/images/docs/myfile.html";
$link = "../../games/game.html";

function resolve_url($current, $link){
$ui = (object)parse_url($current);
$domain = $ui->scheme."://".$ui->host;
$levelsA = preg_split("/\.\.\//", $link);
$levels = 0;
foreach($levelsA as $l){
	if(empty($l)) $levels++;
}
$currentA = preg_split("/\//", $current);
$length = count($currentA);
array_splice($currentA, -$levels - 1);
$currentA[] = preg_replace("/\.\.\//", "", $link);
return implode("/", $currentA);
}

echo resolve_url($location, $link);
?>

 

Thanks!

Link to comment
Share on other sites

found this, which seems too work too:

 

function rel2abs($rel, $base){
    /* return if already absolute URL */
    if (parse_url($rel, PHP_URL_SCHEME) != '') return $rel;

    /* queries and anchors */
    if ($rel[0]=='#' || $rel[0]=='?') return $base.$rel;

    /* parse base URL and convert to local variables:
       $scheme, $host, $path */
    extract(parse_url($base));

    /* remove non-directory element from path */
    $path = preg_replace('#/[^/]*$#', '', $path);

    /* destroy path if relative url points to root */
    if ($rel[0] == '/') $path = '';

    /* dirty absolute URL */
    $abs = "$host$path/$rel";

    /* replace '//' or '/./' or '/foo/../' with '/' */
    $re = array('#(/\.?/)#', '#/(?!\.\.)[^/]+/\.\./#');
    for($n=1; $n>0; $abs=preg_replace($re, '/', $abs, -1, $n)) {}

    /* absolute URL is ready! */
    return $scheme.'://'.$abs;
}

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.