I wanted to read the cookie and calculate its length on server side using php, but can't find any direct method to do so. So how to achieve this task ?
Asked
Active
Viewed 6,346 times
3
-
14 kilobytes per cookie, where the name and the OPAQUE_STRING combine to form the 4 kilobyte limit. – NullPoiиteя Apr 01 '13 at 09:08
-
2what do you mean by length ... ?is it size .. ? – alwaysLearn Apr 01 '13 at 09:09
-
@dreamCoder: yes it is the size – blackhole Apr 01 '13 at 09:11
5 Answers
4
what about this ?
setcookie("user", "Dino babu kannampuzha", time() + 3600);
if (isset($_COOKIE["user"])) {
$data = $_COOKIE["user"];
$serialized_data = serialize($data);
$size = strlen($serialized_data);
echo 'Length : ' . strlen($data);
echo "<br/>";
echo 'Size : ' . ($size * 8 / 1024) . ' Kb';
}
// Output
Length : 21
Size : 0.232 Kb

Dino Babu
- 5,814
- 3
- 24
- 33
-
Note that since the cookie will only be available after the page has been reloaded, the condition will be satisfied only *after* reload. – Boaz Apr 01 '13 at 09:12
-
-
1+1 but does the size limit on cookies include data like expiry time? (which isn't parsed into the $_COOKIE var) – Emissary Apr 01 '13 at 09:13
-
2
-
http://extraconversion.com/data-storage/characters/characters-to-bytes.html If 1 character = 1 byte then why you `n*8/1024` ? I'm very bad on math please excuse me, I'm really can't get it. – vee Jun 13 '17 at 05:23
2
To get the raw cookies and their length:
$rawCookies = isset($_SERVER['HTTP_COOKIE']) ? $_SERVER['HTTP_COOKIE'] : null;
$rawLength = strlen($rawCookies);
echo $rawLength;

Sverri M. Olsen
- 13,055
- 3
- 36
- 52
0
Not sure if this is what you want but you can try this
$start_memory = memory_get_usage();
$cookie = $_COOKIE['YourCookie'];
echo memory_get_usage() - $start_memory-PHP_INT_SIZE * 8;
<?php
setcookie("TestCookie", '10');
$start = memory_get_usage();
$cookie = $_COOKIE['TestCookie'];
echo memory_get_usage() - $start; //116 bytes
?>

alwaysLearn
- 6,882
- 7
- 39
- 67
0
Refer from these resources:
http://extraconversion.com/data-storage/characters/characters-to-bytes.html
Measure string size in Bytes in php
https://mothereff.in/byte-counter
And my screenshot that get cookie size using Firebug.
I use my code from @Dino but change something such as strlen
to mb_strlen
to support unicode.
It becomes:
$data = $_COOKIE['user'];
$name = 'user';
if (!is_scalar($data)) {
$data = serialize($data);
}
$size = mb_strlen($data)+mb_strlen($name);
echo 'Cookie name length : ' . mb_strlen($name) . "<br>\n";
echo 'Cookie content length : ' . mb_strlen($data) . "<br>\n";
echo 'Cookie size : ~' . ($size) . ' Bytes<br>'."\n";
Which is almost close to the size appears in Firebug. I really don't understand why the size must (n*8/1024)
if we refer from the resources above it just 1 character 1 byte except unicode so I have to use mb_strlen
instead of strlen
.

vee
- 4,506
- 5
- 44
- 81