PHP Using parse_url()


Example

parse_url(): This function parses a URL and returns an associative array containing any of the various components of the URL that are present.

$url = parse_url('http://example.com/project/controller/action/param1/param2');

Array
(
    [scheme] => http
    [host] => example.com
    [path] => /project/controller/action/param1/param2
)

If you need the path separated you can use explode

$url = parse_url('http://example.com/project/controller/action/param1/param2');
$url['sections'] = explode('/', $url['path']);

Array
(
    [scheme] => http
    [host] => example.com
    [path] => /project/controller/action/param1/param2
    [sections] => Array
        (
            [0] => 
            [1] => project
            [2] => controller
            [3] => action
            [4] => param1
            [5] => param2
        )

)

If you need the last part of the section you can use end() like this:

$last = end($url['sections']);

If the URL contains GET vars you can retrieve those as well

$url = parse_url('http://example.com?var1=value1&var2=value2');

Array
(
    [scheme] => http
    [host] => example.com
    [query] => var1=value1&var2=value2
)

If you wish to break down the query vars you can use parse_str() like this:

$url = parse_url('http://example.com?var1=value1&var2=value2');
parse_str($url['query'], $parts);

Array
(
    [var1] => value1
    [var2] => value2
)