Handling Duplicate Query Parameters in PHP
PHP's default behavior for handling query strings can be frustrating when dealing with specific protocols like Z39.50 or OpenURL resolvers. When a URL contains multiple parameters with identical names, such as two rft_id entries, the standard $_GET superglobal array only preserves the last value encountered during parsing. This happens because PHP's parse_str() function, which underpins $_GET, treats the query string as a simple key-value map where subsequent keys overwrite previous ones with the same name.
In your specific use case, retrieving both OCLC and Biodiversity Library identifiers requires bypassing the default associative array structure. The solution involves parsing the raw query string manually to preserve all occurrences of duplicate keys.
Manual Query String Parsing
The most reliable approach is to split the $_GET['rft_id'] issue at its root: stop treating the input as an array immediately and parse it as a string instead. You can achieve this using PHP's built-in explode() function combined with str_getcsv(), which handles parsing logic similar to how browsers often handle complex query strings internally.
Here is a practical implementation pattern:
$rawQuery = $_SERVER['QUERY_STRING'];
if ($rawQuery !== '') {
// Split the query string by '&' to get individual parameters
$pairs = explode('&', $rawQuery);
// Prepare an array to hold all values for each key
$allParams = [];
foreach ($pairs as $pair) {
if (strpos($pair, '=') !== false) {
list($key, $value) = explode('=', $pair, 2);
// Decode the value in case it was URL-encoded
$decodedValue = urldecode($value);
// Append the new value to the existing key if it exists
if (isset($allParams[$key])) {
$allParams[$key][] = $decodedValue;
} else {
$allParams[$key] = $decodedValue;
}
} elseif (strpos($pair, '=') === false) {
// Handle parameters without values (e.g., rft_val_fmt=info:ofi/fmt:kev:mtx:book)
list(,$value) = explode('=', $pair, 2);
$allParams[$pair] = $value;
}
}
// Now you can access both values safely
if (isset($allParams['rft_id'])) {
// If there were duplicates, it will be an array now
$ids = $allParams['rft_id'];
// Check if it's a single value or an array of values
if (is_array($ids)) {
foreach ($ids as $id) {
echo "Found ID: " . $id . "<br>";
}
} else {
echo "Found ID: " . $ids . "<br>";
}
}
}
This approach ensures that $_GET['rft_id'] won't silently overwrite your data. By iterating through the raw string, you maintain the exact order and count of every parameter provided by the client.
Why Manual Parsing Is Necessary
You might wonder why a framework or standard library doesn't do this automatically. The answer lies in the design philosophy of the PHP language itself: it assumes query strings represent simple key-value mappings unless explicitly told otherwise. Frameworks like Laravel also rely on this behavior by default for consistency with standard HTTP expectations. However, when integrating with legacy systems or specialized protocols that define duplicate keys as meaningful data, you must step outside the standard abstraction layer.
One potential pitfall with manual parsing is handling URL encoding. The snippet above includes urldecode() to ensure that values like spaces or special characters are handled correctly. Without this, a value containing an encoded space (%20) would break your logic if not decoded first. Additionally, be cautious of edge cases where a parameter has no equals sign but still exists in the string; the code handles this by checking strpos($pair, '=').
Framework Considerations
If you are building this resolver inside a Laravel application, you will find that the framework's request bag does not natively support duplicate keys either. The request->get('rft_id') method will still return only the last value. To access all values in a Laravel context, you must access the raw input stream or the underlying query string directly from the request object:
$raw = $request->getQueryString();
// Then parse using the manual logic shown above
Alternatively, you can utilize the Illuminate\Http\Request class's ability to inspect the original query array if you are working with a custom service provider or a specific middleware layer that exposes the full parsed list. However, for most standard requests, sticking to the raw string manipulation is the safest bet to avoid framework version-specific changes in how input is normalized.
Trade-offs and Best Practices
While manual parsing adds lines of code, it provides deterministic behavior regardless of PHP version or server configuration. The primary trade-off is the loss of convenience; you no longer get a clean associative array out of the box. You must decide at runtime whether a key holds a single value or an array.
In your specific application logic, consider normalizing the result immediately after parsing. If rft_id contains multiple values, treat it as a collection. If it contains one, keep it as a scalar. This normalization step prevents downstream code from needing to check types constantly. Remember that this pattern applies to any scenario where the client sends duplicate keys intentionally, such as multi-value form submissions or specific protocol requirements like Z39.50 metadata retrieval.