Skip to content
Tutorials Center
My learning

Topics

PHP Reference ยท String Functions

PHP parse_url() function

Reference for PHP parse_url(): split a URL into scheme, host, port, path, query and fragment, get a single component, failure cases and security warnings.

parse_url() splits a URL into its components and returns them as an associative array. Only the parts that are present appear as keys, so a URL with no query string has no query key. Pass a component constant as the second argument to get one part directly.

The function does not validate. It is built to be tolerant and will happily split strings that are not real URLs, so treat its output as "what the string looks like", not as proof that the address is safe or reachable.

PHP
<?php
print_r(parse_url("https://example.com:8080/a/b?x=1#top"));

Try it

PHP All the parts of a URL

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

PHP Relative URLs, query parsing and failures

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Syntax

PHP
parse_url(string $url, int $component = -1): int|string|array|null|false
Name Description
$url The URL (or URL-like string) to split.
$component -1 returns the whole array. Otherwise one of PHP_URL_SCHEME, PHP_URL_HOST, PHP_URL_PORT, PHP_URL_USER, PHP_URL_PASS, PHP_URL_PATH, PHP_URL_QUERY, PHP_URL_FRAGMENT.

Return value: an array with any of the keys scheme, host, port, user, pass, path, query and fragment. With $component, a string (or an int for the port), or null if that part is missing. false if the URL is seriously malformed.

Usage notes

  • Missing parts are missing keys. Check with ?? or isset() before reading them.
  • port is an integer, all other parts are strings. The port is only present when the URL names it explicitly.
  • query is the raw string without the ?. Hand it to parse_str() to get an array. The fragment is stripped of its #.
  • Relative references work (/path?x=1, //host/path), but results for odd inputs vary, so parse trusted, absolute URLs when you can.
  • Not a validator or a security check. Strings such as javascript:alert(1) parse fine. To restrict redirects or fetches, compare scheme and host against an allow-list; never test with str_contains($url, "example.com").
  • Not a decoder. Components stay percent-encoded; use rawurldecode() when you need the plain text.
  • Newer API: PHP 8.5 adds the Uri\Rfc3986\Uri class, which follows the standard strictly and throws on invalid input.