1. <?php
  2. /**
  3. * Initializes query string components for a one-off script with synchronous execution.
  4. *
  5. * @return array Associative array of query string parameters. Returns an empty array if no query string is provided.
  6. */
  7. function initializeQueryStringComponents(): array
  8. {
  9. $components = [];
  10. //Get all query parameters
  11. $query_string = get_query_string();
  12. if ($query_string) {
  13. $params = parse_url($query_string, PHP_URL_QUERY);
  14. if ($params) {
  15. // Split the query string into individual parameters
  16. $pairs = explode('&', $params);
  17. foreach ($pairs as $pair) {
  18. // Split each pair into key and value
  19. $parts = explode('=', $pair, 2); // Limit to 2 parts to handle values with '='
  20. if (count($parts) === 2) {
  21. $key = urldecode($parts[0]); // Decode URL-encoded characters
  22. $value = urldecode($parts[1]); // Decode URL-encoded characters
  23. $components[$key] = $value;
  24. }
  25. }
  26. }
  27. }
  28. return $components;
  29. }
  30. /**
  31. * Helper function to retrieve the query string from the URL.
  32. * @return string The query string, or an empty string if there is no query string.
  33. */
  34. function get_query_string(): string {
  35. $url = $_SERVER['REQUEST_URI'];
  36. $query_string = preg_match('/(\?.*)', $url, $matches);
  37. return $query_string ? $matches[1] : '';
  38. }
  39. //Example Usage (for testing)
  40. //$query_params = initializeQueryStringComponents();
  41. //print_r($query_params);
  42. ?>

Add your comment