Server-Side PHP: Part 4: $_COOKIE

Server-Side PHP

PHP is a programming language frequently used for server-side web development.


The superglobal $_COOKIE contains all previously created cookies. Like $_GET and $_SET, it is an array containing information sent to and from clients.

Using setcookie()

In order for a cookie to accessed, it must first exist. The function setcookie() creates cookies. However, and as the PHP manual page warnings, using this function must happen before other functionality due to protocol restrictions. Using setcookie() should be one of the first things done in a file that contains it.

Accessing Cookies

For whatever name is set using the setcookie() function, the Cookie value will exist in the $_COOKIE array as that key.

Cookies also exist after they have been created. While this may make sense at a surface level, the greater depth of the concept often catches newer developers.

Cookies are set as part of the header information during the transfer of the page in which they are a part. Therefore, they do not exist until after the page is loaded. In order to access cookies, the page either needs to be refreshed or otherwise tested after the page fully loads in which the setcookie() function appears.