PHP Exercises : Return some components of an url
PHP : Exercise-8 with Solution
Write a PHP script, which will return the following components of the url 'https://www.w3resource.com/php-exercises/php-basic-exercises.php'.
List of components : Scheme, Host, Path
What is a URL?
URL stands for Uniform Resource Locator. It is used to specify its location on a computer network and a mechanism for retrieving it. A URL is the fundamental network identification for any resource connected to the web (e.g., hypertext pages, images, and sound files).
URLs have the following format:
protocol://hostname/other_information
For example, the URL for w3resource's PHP basic exercises page is:
'https://www.w3resource.com/php-exercises/php-basic-exercises.php';
Sample Solution:
PHP Code:
<?php
// Define the URL to be parsed
$url = 'https://www.w3resource.com/php-exercises/php-basic-exercises.php';
// Parse the URL and store its components in the $url variable
$url = parse_url($url);
// Display the scheme (protocol) of the parsed URL
echo 'Scheme : ' . $url['scheme'] . "\n";
// Display the host (domain) of the parsed URL
echo 'Host : ' . $url['host'] . "\n";
// Display the path of the parsed URL
echo 'Path : ' . $url['path'] . "\n";
?>
Sample Output:
Scheme : http Host : www.w3resource.com Path : /php-exercises/php-basic-exercises.php
Explanation:
Here's a brief explanation of the above exercise:
- $url = 'https://www.w3resource.com/php-exercises/php-basic-exercises.php';
- Defines a URL string to be parsed.
- $url = parse_url($url);
- Parses the defined URL using the "parse_url()" function and stores the components (scheme, host, path, etc.) in the '$url' variable.
- echo 'Scheme : ' . $url['scheme'] . "\n";
- Displays the scheme (protocol) of the parsed URL.
- echo 'Host : ' . $url['host'] . "\n";
- Displays the host (domain) of the parsed URL.
- echo 'Path : ' . $url['path'] . "\n";
- Displays the path of the parsed URL.
Flowchart:
PHP Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Write a PHP script to get the current file name.
Next: Write a PHP script, which changes the color of the first character of a word.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/php-exercises/php-basic-exercise-8.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics