Accessing Cookies Scripts In PHP

Accessing Cookies Scripts In PHP To Access cookies in PHP is very easy: A user can simply read values from the $_COOKIE superglobal array.

To display the pageViews cookie set use :

echo $_COOKIE[“pageViews”]; // Displays “8”

As with $_GET and $_POST , in a real – world situation you should not directly output data from the $_COOKIE array without filtering and/or validating it first. It is easy for an attacker to inject malicious data into the cookies sent to the server.

It is important to realize that a newly created cookie is not available to the scripts via $_COOKIE until the next browser request is made. This is because the first time the script is run, it mainly sends the cookie to the browser. The browser does not return the cookie to the server until it next requests a URL from the server.


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

This code displays nothing ( false ) the first time it is run, because $_COOKIE[ “ pageViews “ ] does not exist. However, 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 is available in the $_COOKIE array.

Similarly, if a user update a cookie’s value, the $_COOKIE array still contains the old value during the execution of the script. Only when the script is run again, by the user reloading the page in her browser, does the $_COOKIE array update with the new value.

Scroll to Top