Lucas Willems
Lucas Willems

Reputation: 7063

Detecting all cookies sent using the setcookie function

I have the following php code :

setcookie('bonjour', 'bonjour', time() + 3600); 
setcookie('aurevoir', 'aurevoir', time() + 3600);

print_r(apache_response_headers());

print_r($_COOKIE);

Which displays that the first time :

Array
(
    [X-Powered-By] => PHP/5.5.0
    [Set-Cookie] => aurevoir=aurevoir; expires=Sat, 31-Aug-2013 10:27:06 GMT; Max-Age=3600
)
Array
(
)

and that the second :

Array
(
    [X-Powered-By] => PHP/5.5.0
    [Set-Cookie] => aurevoir=aurevoir; expires=Sat, 31-Aug-2013 10:26:47 GMT; Max-Age=3600
)
Array
(
    [bonjour] => bonjour
    [aurevoir] => aurevoir
)

The problem is, as you can see, only the second/last cookie is stored in the Set-Cookie of the first array. So, how can I, using the headers array, detect that two cookies are set ?

Upvotes: 2

Views: 207

Answers (1)

hynner
hynner

Reputation: 1352

Use the headers_list() function, like this:

<?php 
setcookie('bonjour', 'bonjour', time() + 5); 
setcookie('aurevoir', 'aurevoir', time() + 5);


var_dump(headers_list());

Which outputs:

array (size=3)
  0 => string 'X-Powered-By: PHP/5.4.12' (length=24)
  1 => string 'Set-Cookie: bonjour=bonjour; expires=Sat, 31-Aug-2013 09:47:48 GMT' (length=66)
  2 => string 'Set-Cookie: aurevoir=aurevoir; expires=Sat, 31-Aug-2013 09:47:48 GMT' (length=68)

Alternativelly you could build a wrapper around setcookie function and store record about every cookie being set, but I guess previous solution should be good enough.

Upvotes: 2

Related Questions