Fetch parameters from a URL string in PHP
This article demonstrates how to fetch the request parameters from a URL string in PHP.
1. Using parse_url() function
You can use the parse_url() function with the parse_str() function to fetch the request parameters from a URL string. The parse_url() function parses a URL string into an associative array of its components. The query string is the value associated with the 'query' key of the returned array. Then you can use the parse_str() function to parse the query string into variables for each of the parameters.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<?php $url = "https://www.google.com/?query=fifa&browser=chrome"; $parsed_url = parse_url($url); parse_str($parsed_url['query'], $params); print_r($params); /* Output: Array ( [query] => fifa [browser] => chrome ) */ ?> |
You can directly get the query string of the URL parsed by passing the predefined constant PHP_URL_QUERY to the second parameter of parse_url(). Note that now parse_url() returns a string.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<?php $url = "https://www.google.com/?query=fifa&browser=chrome"; $parsed_url = parse_url($url, PHP_URL_QUERY); parse_str($parsed_url, $params); print_r($params); /* Output: Array ( [query] => fifa [browser] => chrome ) */ ?> |
If you need a specific query parameter, you can access array elements using the square bracket syntax.
|
1 2 3 4 5 6 7 8 9 10 11 |
<?php $url = "https://www.google.com/?query=fifa&browser=chrome"; $parsed_url = parse_url($url, PHP_URL_QUERY); parse_str($parsed_url, $params); echo $params['browser']; /* Output: chrome */ ?> |
2. Using preg_match() function
You may also use a regex to extract specific parameters from a URL string. In PHP, the preg_match() function is used for performing a regular expression match. Here’s an example of how you could achieve that.
|
1 2 3 4 5 6 7 8 9 10 |
<?php $url = "https://www.google.com/?query=fifa&browser=chrome"; preg_match("/&?browser=([^&]+)/", $url, $matches); echo $matches[1]; /* Output: chrome */ ?> |
3. Using $_GET function
Finally, you may use the $_GET predefined variables to get an associative array of variables passed to the current script via the URL parameters. For example, the following solution outputs "chrome" for the user-entered URL "https://www.google.com/?query=fifa&browser=chrome".
|
1 2 3 4 5 6 7 |
<?php echo $_GET["browser"]; /* Output: chrome */ ?> |
That’s all about fetching the request parameters from a URL string in PHP.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)