PHP Function Reference

PHP parse_url() Function



The PHP parse_url() function parses a URL and returns an associative array which contains its various components.

Syntax

parse_url(url, component)

Parameters

url Required. Specify the URL to parse.
component Optional. Specify one of component (PHP_URL_SCHEME, PHP_URL_HOST, PHP_URL_PORT, PHP_URL_USER, PHP_URL_PASS, PHP_URL_PATH, PHP_URL_QUERY or PHP_URL_FRAGMENT) to retrieve a specific URL component as a string (or an int, in the case of PHP_URL_PORT).

Return Value

  • It return false, if the parameter is malformed URL.
  • If the component parameter is omitted, an associative array is returned. At least one element will be present within the array. Potential keys within this array are:
    • scheme - e.g. http
    • host
    • port
    • user
    • pass
    • path
    • query - after the question mark ?
    • fragment - after the hashmark #
  • If the component parameter is specified, the function returns a string (or an int, in the case of PHP_URL_PORT) instead of an array. If the requested component doesn't exist within the given URL, null will be returned.
Note: The control characters in the components are replaced with underscores (_).

Example: parse_url() example

The example below shows the usage of parse_url() function.

<?php
$url = 'https://www.alphacodingskills.com/index.php?page=PHP#examples';

//parsing the url
print_r(parse_url($url));

echo "\n";

var_dump(parse_url($url, PHP_URL_SCHEME));
var_dump(parse_url($url, PHP_URL_USER));
var_dump(parse_url($url, PHP_URL_PASS));
var_dump(parse_url($url, PHP_URL_HOST));
var_dump(parse_url($url, PHP_URL_PORT));
var_dump(parse_url($url, PHP_URL_PATH));
var_dump(parse_url($url, PHP_URL_QUERY));
var_dump(parse_url($url, PHP_URL_FRAGMENT));
?>

The output of the above code will be:

Array
(
    [scheme] => https
    [host] => www.alphacodingskills.com
    [path] => /index.php
    [query] => page=PHP
    [fragment] => examples
)

string(5) "https"
NULL
NULL
string(25) "www.alphacodingskills.com"
NULL
string(10) "/index.php"
string(8) "page=PHP"
string(8) "examples"

Example: parse_url() example with missing scheme

Consider the example below where the scheme is missing from the URL.

<?php
$url = '//www.alphacodingskills.com/index.php?page=PHP#examples';

//parsing the url
print_r(parse_url($url));
?>

The output of the above code will be:

Array
(
    [host] => www.alphacodingskills.com
    [path] => /index.php
    [query] => page=PHP
    [fragment] => examples
)

❮ PHP URLs Reference