Tuesday, March 16, 2010

php setcookie for array of cookie

On the php manual page for setcookie() function
is says you can use setcookie() to set array of cookies

http://us2.php.net/manual/en/function.setcookie.php

This is convenient, but also a bit misleading. It leads you to believe that you are setting just one cookie with the array of values, but in fact the browser actually setting new cookie for each new array element.

So you may be setting 10 different cookies and not even knowing about it. A better solution is to set just one cookie with the name/value pairs like
userid=12331&name=john&group=admins&firstvisit=20091010

You can use http_build_query() to build a string that will then become your cookie value.

See, it looks similar to url.

To get values from the cookie, just get the cookie using the
$val = $_COOKIE['cookiename'];
and then:
parse_str($val, $aVars);
now the $aVars contains the name => value pairs
Just treat the values with caution just like any other user-passed variables. Validate, sanitize, whatever you normally do with values passed by user.

No comments:

Post a Comment