Use parse_url()
with parse_str() functions
Use parse_url()
with parse_str()
to get parameters from URL String in PHP. The parse_url()
function is used to return the components of a URL by parsing it and parse_str()
is used to create an associate array of query parameters and their values.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<?php $url = "http://www.temp.com/html/codes.php?id=10&category=main#top"; $url_parts = parse_url($url); // Get the query string from the URL $query_str = $url_parts['query']; // Parse the query string into an array of key/value pairs parse_str($query_str, $query_params); // Print the array of query parameters print_r($query_params); |
1 2 3 4 5 6 7 |
Array ( [id] => 10 [category] => main ) |
Once you have the array of query parameters, you can easily access the individual values using the array keys. For example, to access the value of the id and category parameter, you could use the following code:
1 2 3 4 |
echo $query_params['id']; echo $query_params['category']; |
1 2 3 |
10main |
We used parse_url()
function to return the components of a URL by parsing it in form of associate array.
parse_url() function takes a string containing the URL as an argument and returns an associative array that contains its various components.
The following table lists the components that can be retrieved by this function:
scheme
: specifies the protocol to be used to access the resource on the Internet.host
: specifies the host name or the IP address of the server.port
: specifies the port number to be used on the server.user
: specifies the username to be used for logging into the server.pass
: specifies the password to be used for logging into the server. path Specifies the path to be used on the server.query
: specifies the query string to be sent to the server.fragment
: specifies the fragment identifier.
Let’s have an example
The following example shows how to use the parse_url()
function:
1 2 3 4 |
<?php $url = "http://www.temp.com/html/codes.php?id=10&category=main#top"; print_r(parse_url($url)); |
This will produce the following result:
1 2 3 4 5 6 7 8 9 10 |
Array ( [scheme] => http [host] => www.temp.com [path] => /html/codes.php [query] => id=10&category=main [fragment] => top ) |
If you want to retrieve a specific component from the URL, you can use the following syntax:
1 2 3 |
parse_url($url, $component); |
The $component
parameter specifies the component to be retrieved.
For example, if you want to retrieve only the query string from the URL, you can use the following code:
1 2 3 4 |
<?php $url = "http://www.temp.com/html/codes.php?id=10&category=main#top"; print_r(parse_url($url, PHP_URL_QUERY)); |
This will produce the following result:
1 2 3 |
id=10&category=main |
Once we have query parameters, we used parse_str()
to parse query string into an array of key/values pairs.
parse_str() parses the String into array of variables.
That’s all about how to get parameters from URL String in PHP.