PHP - Accessing Cookies in Your Scripts

Introduction

To access cookies in PHP, read values from the $_COOKIE super global array.

This associative array contains a list of all the cookie values sent by the browser in the current request, keyed by cookie name.

To display the pageViews cookie, you could use:

echo $_COOKIE[" pageViews" ]; // Displays" 8" 

A newly created cookie isn't available to your scripts via $_COOKIE until the next browser request is made.

For example:

setcookie(" pageViews" , 7, 0," /" ," " , false, true);
echo isset($_COOKIE[" pageViews" ]);

This code displays nothing (false) the first time it's run, because$_COOKIE[" pageViews"] doesn't exist.

If the user reloads the page to run the script again, the script displays 1 (true) because the browser has sent the pageViews cookie back to the server, so it's available in the $_COOKIE array.

If you update a cookie's value, the $_COOKIE array still contains the old value during the execution of the script.

Related Topic