Storing PHP arrays in cookies

Storing PHP arrays in cookies

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

The Cookie Size Limit and Array Serialization

Cookies are stateful tokens, but they are also extremely restrictive storage mediums. When you attempt to store a PHP array directly in a cookie, the most common pitfall is ignoring the character limit imposed by browsers and servers. A standard cookie has a maximum size of approximately 4KB, depending on the browser. Beyond that, the cookie will simply be truncated or rejected.

Your source code snippet demonstrates creating a multidimensional array structure:

$number_ticket = 2;
$info[7][5] = 1;
$info[8][5] = 1;

While this syntax is valid for constructing an associative or indexed array in memory, sending this entire structure to a client via $_COOKIE or setcookie() fails as soon as the serialized data exceeds the limit. If you use serialize() on that array without checking the resulting string length, you risk breaking the session state for users with certain configurations or older browsers.

Serialization and Compression

The standard approach to storing arrays in cookies is serialization. PHP provides two main functions: serialize() and json_encode().

serialize() creates a format specific to PHP. It preserves type information (integers, booleans, objects), which can be useful if you need to reconstruct the exact data structure later. However, it produces verbose strings with many special characters like s: for strings or a: for arrays.

$data = [7 => 1, 8 => 1];
$cookieValue = serialize($data);
setcookie('ticket_info', $cookieValue);

If you check the length of $cookieValue, it will quickly approach or exceed the 4KB limit as you add more elements. Furthermore, serialize() is not universally supported in JavaScript; if your frontend needs to read this data, you cannot use serialize().

json_encode() is generally the safer choice for cross-platform compatibility. It produces a standard JSON string that can be easily parsed by any modern language or framework. While it lacks type preservation (distinguishing between 1 and "1"), it is more compact and readable.

$data = [7 => 1, 8 => 1];
$cookieValue = json_encode($data);
setcookie('ticket_info', $cookieValue);

The Real Constraint: Character Count

The primary technical constraint is not the memory available on the server, but the HTTP header size and browser implementation limits. If you store an array in a cookie, you must account for the serialized length before setting the cookie.

A common mistake is assuming that because the data fits in your application's memory, it fits in the cookie. You must explicitly check the byte length of the encoded string:

if (strlen(json_encode($info)) > 4095) {
    // Fallback to database storage or splitting cookies
}

If the data exceeds this limit, you cannot simply truncate it arbitrarily, as that would corrupt the array structure and prevent deserialization on the client side. Instead, you should implement a fallback strategy, such as storing the cookie for small datasets and falling back to server-side session storage ($_SESSION) or a database for larger payloads.

Security Considerations

Storing arrays in cookies introduces security risks if not handled correctly. The most critical risk is Cross-Site Scripting (XSS). Since cookies are sent with every request, any value stored in a cookie is technically executable code on the client side if it contains malicious scripts.

When using json_encode(), ensure you use the appropriate flags to minimize XSS risks, though JSON itself does not execute scripts. The danger arises when you read the cookie back and echo it directly into an HTML response without sanitization.

// Dangerous: Directly echoing raw cookie data
echo $_COOKIE['ticket_info']; 

// Safer: Sanitize before output
echo htmlspecialchars($_COOKIE['ticket_info'], ENT_QUOTES, 'UTF-8');

Additionally, always set the HttpOnly and Secure flags when setting the cookie. The HttpOnly flag prevents client-side JavaScript from accessing the cookie via document.cookie, mitigating XSS attacks that try to steal session data or ticket information stored in the cookie.

When to Use LaravelCompany Resources

If you are working within a larger ecosystem, managing complex state like arrays in cookies often points toward architectural decisions rather than just syntax tweaks. For instance, if your application relies heavily on server-side sessions and needs to integrate with specific enterprise solutions, resources from https://laravelcompany.com can provide guidance on session handling best practices. However, for simple array storage, sticking to the built-in json_encode() and strict length checks is the most robust solution without introducing external dependencies.

The decision to store an array in a cookie should be driven by the need for client-side accessibility of that specific data. If the data is only needed on the server, use sessions or databases. If it must be available to JavaScript, use JSON serialization and respect the 4KB boundary rigorously.

Our network