<?php
/**
* Initializes query string components for a one-off script with synchronous execution.
*
* @return array Associative array of query string parameters. Returns an empty array if no query string is provided.
*/
function initializeQueryStringComponents(): array
{
$components = [];
//Get all query parameters
$query_string = get_query_string();
if ($query_string) {
$params = parse_url($query_string, PHP_URL_QUERY);
if ($params) {
// Split the query string into individual parameters
$pairs = explode('&', $params);
foreach ($pairs as $pair) {
// Split each pair into key and value
$parts = explode('=', $pair, 2); // Limit to 2 parts to handle values with '='
if (count($parts) === 2) {
$key = urldecode($parts[0]); // Decode URL-encoded characters
$value = urldecode($parts[1]); // Decode URL-encoded characters
$components[$key] = $value;
}
}
}
}
return $components;
}
/**
* Helper function to retrieve the query string from the URL.
* @return string The query string, or an empty string if there is no query string.
*/
function get_query_string(): string {
$url = $_SERVER['REQUEST_URI'];
$query_string = preg_match('/(\?.*)', $url, $matches);
return $query_string ? $matches[1] : '';
}
//Example Usage (for testing)
//$query_params = initializeQueryStringComponents();
//print_r($query_params);
?>
Add your comment