The page you were looking for doesn't exist.

You may have mistyped the address or the page may have moved.

If you are the application owner check the logs for more information.

Python’s urlparse.urljoin equivalent in PHP

I’ve searched the web carefully and found nothing but spam while looking for the equivalent of python’s urlparse.urljoin for PHP so I have decided to write my own function for this purpose. After I was finished writing it and tested it a bit, I was so happy with the result that I decided to share the function:

function urljoin( $url1, $url2 ) {
	$p1 = parse_url( $url1 );
	$p2 = parse_url( $url2 );
	$r = array_merge( $p1, $p2 );
	$spc = array( 'query', 'fragment', 'path' );
	foreach( $p1 as $k => $v )
		if( !isset( $p2[ $k ] ) && in_array( $k, $spc ) )
			unset( $r[ $k ] );
	if( isset( $r['path'] ) && !isset( $p2['host'] ) ) {
		if( strpos( $url2, '/' ) !== 0 ) {
			$path1 = explode( '/', isset( $p1['path'] ) ? $p1['path'] : '' );
			$path2 = explode( '/', isset( $p2['path'] ) ? $p2['path'] : '' );
			array_pop( $path1 );
			foreach( $path2 as $px ) {
				switch( $px ) {
					case '..':
						array_pop( $path1 );
						break;
					case '.':
						# nothing
						break;
					default:
						$path1[] = $px;
						break;
				}
			}
			$r['path'] = implode( '/', $path1 );
		}
	}
	$out = ( isset( $r['scheme'] ) ? $r['scheme'] . '://' : 'http://' ) .
		( isset( $r['user'] ) ? $r['user'] . ( isset( $r['pass'] ) ? ':' . $r['pass'] : '' ) . '@' : '' ) .
		$r['host'] . ( isset( $r['port'] ) ? ':' . $r['port'] : '' ) . '/' .
		ltrim( ( isset( $r['path'] ) ? $r['path'] : '' ), '/' ) .
		( isset( $r['query'] ) ? '?' . $r['query'] : '' ) .
		( isset( $r['fragment'] ) ? '#' . $r['fragment'] : '' );
	return $out;
}

Happy coding :D

About The Author

Hi, I’m a 23 years old web-developer that loves creating websites using PHP and JavaScript. I enjoy working with WordPress and building custom CMSs using the latest frameworks and technologies. In my 5 years of work I’ve created all sorts of websites using frameworks and tools like ExtJS, jQuery, Scriptaculous and Prototype, Symfony, Prado and CodeIgniter using either MySQL or MongoDB.

0 Comments