How to get the scheme, host, port, and path from a complete URL using PHP?

Software Engineer@Datasoft Systems Bangladesh Limited BSc. in CSE
Suppose you have some URLs like:
$urls = [
'https://www.hishabkitab.com/dashboard',
'http://hishabkitab.com:8080',
'http://localhost:5034',
'https://ohr.hishabkitab.com'
];
If you want only a host from the URLs. You can use PHP built-in function parse_url() . Example
function get_host($url){
$parsed_url = parse_url($url);
return $parsed_url['host'] ?? '';
}
foreach($urls AS $url){
echo get_host($url) . '<br';
}
The output will be like this:
www.hishabkitab.com
hishabkitab.com
localhost
ohr.hishabkitab.com
But if you want only port, just change the function like this:
function get_port($url){
$parsed_url = parse_url($url);
return $parsed_url['port'] ?? '';
}
The same applies to the get scheme.



