Skip to content
PHP Logo

What are the best practices for handling partial URLs with parse_url in PHP?

When using parse_url in PHP to extract parts of a URL, it is important to handle cases where the URL is incomplete or missing certain components. One common issue is when the URL does not contain a scheme (http:// or https://), which can cause parse_url to return unexpected results. To handle this, you can prepend a default scheme to the URL before parsing it.

php
$url = "example.com/path/to/resource";

// Prepend default scheme if missing
if (!parse_url($url, PHP_URL_SCHEME)) {
    $url = 'http://' . $url;
}

$parsed_url = parse_url($url);

// Access individual components of the URL
$scheme = $parsed_url['scheme'];
$host = $parsed_url['host'];
$path = $parsed_url['path'];

// Output the parsed URL components
echo "Scheme: $scheme\n";
echo "Host: $host\n";
echo "Path: $path\n";