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 print_r(parse_url("https://example.com:8080/a/b?x=1#top"));
Try it
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.
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
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
??orisset()before reading them. portis an integer, all other parts are strings. The port is only present when the URL names it explicitly.queryis the raw string without the?. Hand it toparse_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, compareschemeandhostagainst an allow-list; never test withstr_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\Uriclass, which follows the standard strictly and throws on invalid input.