Accessing Cookie Data

Jun 15, 2009 Author: SEO

Cookie data is usually sent to the server using a single request header. The PHP interpreter takes care of automatically separating the individual cookies from the header and places them in the $_COOKIE superglobal array:

if ($_COOKIE[’hide_menu’] == 1) {// hide menu}

Cookie values must be scalar; of course, you can create arrays using the same array notation that we used for $_GET and $_POST:

setcookie("test_cookie[0]", "foo");
setcookie("test_cookie[1]", "bar");
setcookie("test_cookie[2]", "bar");

At the next request, $_COOKIE[’test_cookie’] will automatically contain an array. You should, however, keep in mind that the amount of storage available is severely limited—therefore, you should keep the amount of data you store in cookies to a minimum, and use sessions instead.

IMPORTANT:Remember that setting cookies is a two-stage process: first, you send the cookie to the client, which will then send it back to you at the next request. Therefore, the $_COOKIE array will not be populated with new information until the next request comes along.

There is no way to “delete” a cookie—primarily because you really have no control over how cookies are stored and managed on the client side. You can, however, call setcookie with an empty string, which will effectively reset the cookie:

 setcookie("hide_menu", false, -3600);

views 4983
  1. Add New Comment