1. <?php
  2. /**
  3. * Indexes cookie content with defensive checks.
  4. *
  5. * @return array Associative array of cookie names and their values.
  6. */
  7. function indexCookies(): array
  8. {
  9. $cookies = [];
  10. // Check if the 'కుంటున్నాము' cookie exists.
  11. if (isset($_COOKIE['కుంటున్నాము'])) {
  12. $cookies['కుంటున్నాము'] = $_COOKIE['కుంటున్నాము'];
  13. }
  14. //Check if the 'user_id' cookie exists and is an integer.
  15. if (isset($_COOKIE['user_id']) && is_numeric($_COOKIE['user_id'])) {
  16. $cookies['user_id'] = (int)$_COOKIE['user_id']; //Cast to integer
  17. } else {
  18. //Handle the case where user_id is not a number.
  19. $cookies['user_id'] = null; //Or set a default value.
  20. error_log("Warning: 'user_id' cookie is not a number.");
  21. }
  22. //Check if the 'timestamp' cookie exists and is a valid timestamp.
  23. if (isset($_COOKIE['timestamp']) && is_int($_COOKIE['timestamp'])) {
  24. $cookies['timestamp'] = date("Y-m-d H:i:s", $_COOKIE['timestamp']); // Format timestamp
  25. } else {
  26. $cookies['timestamp'] = null;
  27. error_log("Warning: 'timestamp' cookie is not a valid timestamp.");
  28. }
  29. // Defensive check: Sanitize cookie values.
  30. foreach ($cookies as $name => $value) {
  31. if (is_string($value)) {
  32. $cookies[$name] = htmlspecialchars($value, ENT_QUOTES, 'UTF-8'); //Prevent XSS
  33. }
  34. //Ensure the value is an array if it should be. This is a basic example, expand as needed.
  35. if (is_array($value)) {
  36. $cookies[$name] = json_decode($value, true); //Decode json. Handle errors gracefully.
  37. if (json_last_error() !== JSON_ERROR_NONE) {
  38. $cookies[$name] = null;
  39. error_log("Warning: Invalid JSON in cookie '$name'.");
  40. }
  41. }
  42. }
  43. return $cookies;
  44. }
  45. //Example usage:
  46. $cookieData = indexCookies();
  47. print_r($cookieData);
  48. ?>

Add your comment