blackhole
blackhole

Reputation: 163

calculate Cookie Size in PHP

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 ?

Upvotes: 4

Views: 6751

Answers (5)

vee
vee

Reputation: 4755

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. enter image description here

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.

Upvotes: 0

alwaysLearn
alwaysLearn

Reputation: 6950

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   
  ?>

Upvotes: 0

Dino Babu
Dino Babu

Reputation: 5809

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

Upvotes: 4

Sverri M. Olsen
Sverri M. Olsen

Reputation: 13283

To get the raw cookies and their length:

$rawCookies = isset($_SERVER['HTTP_COOKIE']) ? $_SERVER['HTTP_COOKIE'] : null;
$rawLength  = strlen($rawCookies);
echo $rawLength;

Upvotes: 2

Majid Fouladpour
Majid Fouladpour

Reputation: 30252

strlen($_COOKIE['cookie_name'])?

Upvotes: 0

Related Questions