PHP Access Cookies
In this chapter you will learn:
- How to access cookie values
- Example - To display the pageViews cookie set
- 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: