Codectionary / Developer documentation / PHP

PHP URL components

parse_url breaks a URL into components such as scheme, host, path and query. Parsing is not validation: even some partial or invalid URL strings can produce components.

Syntax

parse_url($url, PHP_URL_HOST)

Examples

PHP URL components

Run as a PHP 8.0+ CLI script, for example php example.php. The multibyte example additionally requires mbstring.

<?php
$parts = parse_url('https://example.com:8443/docs?page=2#intro');
if ($parts === false) throw new InvalidArgumentException('Cannot parse URL');
echo $parts['host'], PHP_EOL;
echo $parts['path'], PHP_EOL;
echo $parts['query'], PHP_EOL;
  1. Output: example.com, /docs, then page=2. The query value is still encoded text, not an associative array.

Best practices

  • Check for missing components. Apply a deliberate scheme and destination policy before using untrusted URLs for redirects or network access.

Runtime & versions

PHP runtime on a server or CLI. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

PHP Manual

Specifications & further reading