How to build an absolute url in php

Posted at 5:50 pm in development, 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.

 

Written by Stefano Forenza on April 30th, 2007

3 Responses to 'How to build an absolute url in php'

Subscribe to comments with RSS or TrackBack to 'How to build an absolute url in php'.

  1. Abdou | 9 Sep 08 at 3:47 pm

    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 | 9 Sep 08 at 4:12 pm

    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 | 10 Sep 08 at 1:32 pm

    Thanks a lot Stefano.

Leave a Reply