PHP Script for Extracting URL Components: Scheme, Host, and Path

By Shahnail Khan Last updated : December 12, 2023

Problem statement

Write a PHP script, which will return the following components of the URL-

List of components: Scheme, Host, Path
Expected Output:
Scheme: http
Path: /php/


To understand this solution better, you should have the basic knowledge of the following PHP topics:

Displaying the components of the URL using PHP Script

In PHP, the variables are declared using the $ symbol followed by the variable name. Unlike other programming languages, PHP does not require explicit declaration of variable types. It can only contain letters, numbers, and underscores.

For displaying the components of the URL in PHP, we use the parse_url() function. The parse_url() function in PHP is used to break down a URL into its components (Scheme, Host, and Path). It takes a URL string as input and returns an associative array containing the various parts of the URL.

Let's take an example to understand this function better.

PHP Script for Extracting URL Components: Scheme, Host, and Path

$url = "";

// Parse the URL
$url_components = parse_url($url);

// Output the result


The output of the above program is:

Array ( [scheme] => https [host] => [path] => /path/file.php [query] => name=value [fragment] => fragment )

URL Components

Explanation of the components:

  • scheme: The protocol used (e.g., "https").
  • host: The domain or server name (e.g., "").
  • path: The specific resource or location on the server (e.g., "/path/file.php").
  • query: Any query parameters present in the URL (e.g., "name=value").
  • fragment: The fragment identifier or anchor (e.g., "fragment").

PHP script for the given problem statement: Extracting different components

In the below PHP code, we are displaying the different components of URL using PHP.

$url = "";

// Parse the URL
$url_components = parse_url($url);

// Extract components
$scheme = $url_components["scheme"];
$host = $url_components["host"];
$path = $url_components["path"];

// Display the output
echo "Scheme: $scheme" . "<br>";
echo "Host: $host" . "<br>";
echo "Path: $path" . "<br>";


The output of the above code is:

Scheme: https
Path: /php/

Code Explanation

In this PHP script, we're working with a URL: "".

We use a function called parse_url($url) to break down this web address into small components.

After breaking down the URL, we create three variables:

  • $scheme: This is like the protocol or method used to access the web page. In this case, it's "https".
  • $host: This is the main address of the website, like "".
  • $path: This represents the specific location or page on the website, here it's "/php/".

Finally, we display these pieces using echo statements.

More PHP Programs »

All PHP Programs

Comments and Discussions!

Load comments ↻

Copyright © 2024 All rights reserved.