How to build an absolute url in php

Today, I was looking for a way to make an url absolute.

Ok, it’s easy. Guess I should think some good excuse for not being to able to do it in 5 minutes. The sad reality is I ended digging on google (again).

I am posting what I found, for (main, and) your reference.

A working one

Update: the function I found didn’t pass my testcases. I had to craft one myself. A raw one, but this should work (really).

I apologize for ugly code, I just wanted to get something fast.

function absolutizeUrl ( $u, $p )
{
	$url = parse_url( $u );
	$page = parse_url( $p );
	if ( strpos( $u , '/' ) === 0 )
	{
		//already absolute		
	} else {
		$basePath = '';
		if (
			isset( $page[ 'path' ] )
			&& strpos( ltrim( $page[ 'path' ], '/' ), '/' )
		)
		{
			$baseTokens = explode( '/', $page[ 'path' ] );
			array_pop( $baseTokens ); // strip basename			
			$baseTokens[] = $u;
			$u = join( '/', $baseTokens );
		}
	}
	if ( ! isset( $url[ 'host' ]))
	{
		$u = 'http://'.$page[ 'host' ].'/'.ltrim( $u, '/' );
	}
	return $u;
}

The bad one I found

Note: this is not error_reporting( E_ALL ) safe. You may have to edit (I had) to avoid stupid notices on the screen.

function absolutizeUrl( $relative, $absolute )
{
	extract(parse_url($absolute));
	if($relative{0} == '/') {
		$cparts = array_filter(explode("/", $relative));
	}
	else
	{
		$aparts = array_filter(explode("/", $path));
		$rparts = array_filter(explode("/", $relative));
		$cparts = array_merge($aparts, $rparts);
		foreach($cparts as $i => $part)
		{
			if($part == '.')
			{
				$cparts[$i] = null;
			}
			if($part == '..')
			{
				$cparts[$i - 1] = null;
				$cparts[$i] = null;
			}
		}
		$cparts = array_filter($cparts);
	}
	$path = implode("/", $cparts);
	$url = "";
	if($scheme)
	{
		$url = "$scheme://";
	}
	if($user)
	{
		$url .= "$user";
		if($pass)
		{
		$url .= ":$pass";
		}
		$url .= "@";
	}
	if($host)
	{
		$url .= "$host/";
	}
	$url .= $path;
	return $url;
}

Found it here.

This seems like a great time to subscribe my RSS !

5 responses to “How to build an absolute url in php”

  1. Abdou

    Hello
    Please is there any predifined variable or simple mechanism to get the absolute URL of the current php script beig parsed, jus as or __FILE__ (this is an OS pathname).

    Thanks

  2. Stefano Forenza

    Hello, to my knowledge there’s no such method. If you’re not using Apache URL rewriting you could obtain it like this:

    $url = ‘http://'.$_SERVER'SERVER_NAME'.substr( __FILE__, strlen($_SERVER['DOCUMENT_ROOT']));

  3. Abdou

    Thanks a lot Stefano.

  4. nash

    Your first script cannot handle fancy relative URLs:

    ../somepage.html
    ../../somepage.html
    ?a=x&b=y
    etc.

    And it is even worse for the second script. Here’s a shorter and working script:

    http://nashruddin.com/PHP_Script_for_Converting_Relative_to_Absolute_URL

  5. Didier

    I found one that also allows parent directories in relative URL:
    http://web-o-blog.blogspot.com/2011/04/function-absoluteurlbaseurl-relativeurl.html

Leave a Reply

Bills

Don’t forget to Subscribe

Latest Activity

Posts

  • Google this is ridiculous
    Google you’re doing it wrong. Very wrong. This is utterly ridiculous. It’s a screenshot with a standard Firefox browser, in the standard screen resolution (1280×800), on Read More
  • A step back from the open source
    One month ago, I created my first Android app. While the app was a paid one, the reception has been outstanding. I’ve gotten a fair amount Read More
  • Facebook shuts down EventPress development.
    When you’re a big company, especially one that makes its money on free web services and advertising, it’s very easy to say you love open Read More
  • Why Android is laggy
    Great post from Andrew Munn explaining some key differences between Android and iPhone/iOs, especially when it comes to rendering and smoothness of animations and why Read More
  • Google Plus keeps your data as much as Facebook does
    When you delete an account from Google+, Google promises you to delete all the data associated with your G+ profile. Well, I deleted mine some time Read More