Retrieving Multiple Parameters with the Same Name from URLs in PHP
PHP's $_GET superglobal variable conveniently provides access to URL parameters, but it has a limitation: for parameters with the same name, it returns only the last value. This can hinder applications that need to handle multiple occurrences of specific parameters in URLs.
Consider the example of an OpenURL resolver, which may encounter URLs with multiple instances of the "rft_id" parameter:
ctx_ver=Z39.88-2004 &rft_id=info:oclcnum/1903126 &rft_id=http://www.biodiversitylibrary.org/bibliography/4323 &rft_val_fmt=info:ofi/fmt:kev:mtx:book &rft.genre=book &rft.btitle=At last: a Christmas in the West Indies. &rft.place=London, &rft.pub=Macmillan and co., &rft.aufirst=Charles &rft.aulast=Kingsley &rft.au=Kingsley, Charles, &rft.pages=1-352 &rft.tpages=352 &rft.date=1871
Retrieving both values of "rft_id" using $_GET would be problematic, as it would only return the second value ("http://www.biodiversitylibrary.org/bibliography/4323"), overwriting the first.
To address this challenge, we can utilize a more sophisticated approach:
$query = explode('&', $_SERVER['QUERY_STRING']); $params = array(); foreach ($query as $param) { // Handling cases where $param lacks an '=' if (strpos($param, '=') === false) { $param .= '='; } list($name, $value) = explode('=', $param, 2); $params[urldecode($name)][] = urldecode($value); }
This code parses the query string into individual parameters, with each key-value pair stored in the $params array. Values for parameters with the same name are stored as an array within the $params array.
For the example URL, the result would be:
array( 'ctx_ver' => array('Z39.88-2004'), 'rft_id' => array('info:oclcnum/1903126', 'http://www.biodiversitylibrary.org/bibliography/4323'), // ... other parameters ... )
Using this approach, you can conveniently access both values of "rft_id" or any other parameter that may appear multiple times in a URL.
The above is the detailed content of How to Retrieve Multiple Parameters with the Same Name from URLs in PHP?. For more information, please follow other related articles on the PHP Chinese website!