Parsing URL in PHP using parse_url()

Posted on Jul 29, 2022

Learn how to parse URL in php with the parse_url() function

Photo from Unsplash

To parse a URL with PHP, you need to use the built-in parse_url() function.

The parse_url() function takes a URL string and returns an associative array containing the URL’s components.

The syntax of the function is as follows:

    string $url,
    int $component = -1
): int|string|array|null|false

The parse_url() function accepts two parameters:

  • The required $url string to parse
  • The optional $component integer tells the function to retrieve a specific URL component

Here’s an example of calling the parse_url() function:


$url = parse_url("");

// 👇 output
// Array
// (
//     [scheme] => https
//     [host] =>
//     [path] => /php-parse-url
// )

The above code shows how parse_url() returns an associative array of three elements: the scheme, host, and path elements.

Depending on your URL form, the function can return the elements below:

  • scheme
  • host
  • port
  • user
  • pass
  • path
  • query
  • fragment

You can select a specific component as follows:


Here’s an example of retrieving only the URL’s host:

echo parse_url(

// 👇 output:
// -> string

The component you wish to retrieve will be returned as a string except for PHP_URL_PORT which will return an int.

When the component doesn’t exist, the function returns null.

For more information and examples, you can visit the parse_url documentation.

Now you’ve learned how to parse a URL using PHP. Good work! 👍

Level up your programming skills

I'm sending out an occasional email with the latest programming tutorials. Drop your email in the box below and I'll send new stuff straight into your inbox!

No spam. Unsubscribe anytime.