How to convert URL to array in PHP

263 views 5 months ago PHP

An URL is the string of many data. URL contains domain, host, parameters scheme, path etc. When you are handling external source URL, you may want to validate domain and schemen or get data from query string.

PHP has in-built parse_url function which returns associative array of url components from the url. Invalid URL returns as false

Syntax:

parse_url($url, $component);

Parameters:

$url URL which you want to be parsed
$component optional specific component name to be return instead of all components(PHP_URL_SCHEME, PHP_URL_HOST, PHP_URL_PORT, PHP_URL_USER, PHP_URL_PASS, PHP_URL_PATH, PHP_URL_QUERY and PHP_URL_FRAGMENT)

Example:

The below example returns the following url components from the url.

<?php
$url = 'https://harsukh21:[email protected]:8800/user/data?limit=10&skip=50#stop_end';
print_r(parse_url($url));

response:

Array
(
[scheme] => https
[host] => api.laravelcode.com
[port] => 8800
[user] => harsukh21
[pass] => 123456
[path] => /user/data
[query] => limit=10&skip=50
[fragment] => stop_end
)

With this response you can validate whether the domain is SSL certified or not. You can also get get parameters from the URL using this method.

If the given URL is not valid, the function simply returns false.

I hope you liked this article and will help in your web development.

Author : Harsukh Makwana
Harsukh Makwana

Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on [email protected]