python-logo

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

0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>