<?php
/**
* Indexes cookie content with defensive checks.
*
* @return array Associative array of cookie names and their values.
*/
function indexCookies(): array
{
$cookies = [];
// Check if the 'కుంటున్నాము' cookie exists.
if (isset($_COOKIE['కుంటున్నాము'])) {
$cookies['కుంటున్నాము'] = $_COOKIE['కుంటున్నాము'];
}
//Check if the 'user_id' cookie exists and is an integer.
if (isset($_COOKIE['user_id']) && is_numeric($_COOKIE['user_id'])) {
$cookies['user_id'] = (int)$_COOKIE['user_id']; //Cast to integer
} else {
//Handle the case where user_id is not a number.
$cookies['user_id'] = null; //Or set a default value.
error_log("Warning: 'user_id' cookie is not a number.");
}
//Check if the 'timestamp' cookie exists and is a valid timestamp.
if (isset($_COOKIE['timestamp']) && is_int($_COOKIE['timestamp'])) {
$cookies['timestamp'] = date("Y-m-d H:i:s", $_COOKIE['timestamp']); // Format timestamp
} else {
$cookies['timestamp'] = null;
error_log("Warning: 'timestamp' cookie is not a valid timestamp.");
}
// Defensive check: Sanitize cookie values.
foreach ($cookies as $name => $value) {
if (is_string($value)) {
$cookies[$name] = htmlspecialchars($value, ENT_QUOTES, 'UTF-8'); //Prevent XSS
}
//Ensure the value is an array if it should be. This is a basic example, expand as needed.
if (is_array($value)) {
$cookies[$name] = json_decode($value, true); //Decode json. Handle errors gracefully.
if (json_last_error() !== JSON_ERROR_NONE) {
$cookies[$name] = null;
error_log("Warning: Invalid JSON in cookie '$name'.");
}
}
}
return $cookies;
}
//Example usage:
$cookieData = indexCookies();
print_r($cookieData);
?>
Add your comment