PHP Access Cookies

In this chapter you will learn:

  1. How to access cookie values
  2. Example - To display the pageViews cookie set
  3. Refresh to get the cookie data

How

We can access cookies in PHP from the $_COOKIE superglobal array.

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

Example 1

To display the pageViews cookie set.


<?PHP
setcookie( "pageViews", 7, 0, "/", "", false, true );  
echo $_COOKIE["pageViews"]; // Displays "8"     
?>

Refresh

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

Because the first time your script is run, it merely sends the cookie to the browser. The browser doesn't return the cookie to the server until it next requests a URL from the server. For example:


<?PHP
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.

Reloading the page to run the script again, we can see that the script displays 1 because the browser has sent the pageViews cookie back to the server.

Next chapter...

What you will learn in the next chapter:

  1. How to delete a cookie
  2. Example - delete a cookie
  3. Note for cookie delete
Home » PHP Tutorial » PHP Cookie
PHP Cookies
PHP Cookie Components
PHP setcookie() function
PHP Access Cookies
PHP Remove Cookies