Page 315 - Beginning PHP 5.3
P. 315
Chapter 10: Preserving State With Query Strings
Accessing Cookies in Your Scripts
Accessing cookies in PHP is very easy: You simply read values from the $_COOKIE superglobal array. As
you ’ d imagine, this associative array contains a list of all the cookie values sent by the browser in the
current request, keyed by cookie name.
So to display the pageViews cookie set in the previous example, you could use:
echo $_COOKIE[“pageViews”]; // Displays “8”
As with $_GET and $_POST , in a real - world situation you shouldn ’ t directly output data from the
$_COOKIE array without filtering and/or validating it first. It ’ s easy for an attacker to inject malicious
data into the cookies sent to the server.
It ’ s important to realize that a newly created cookie isn ’ t available to your scripts via $_COOKIE until
the next browser request is made. This is 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:
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. 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 ’ s available in the $_COOKIE array.
Similarly, if you 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.
Removing Cookies
If you no longer need a cookie that ’ s stored on the user ’ s browser, you can instruct the browser to delete
it. To delete a cookie, you call setcookie() with the cookie name and any value (such as an empty
string), and pass in an expires argument that is in the past. This immediately expires the cookie on the
browser, ensuring that it is deleted. You should also pass exactly the same path , domain , and other fields
that you used when you first created the cookie to ensure that the correct cookie is deleted:
setcookie( “fontSize”, “”, time() - 3600, “/”, “.example.com”, false, true );
This example sets the fontSize cookie ’ s expiry time to one hour in the past, which effectively deletes it
from the browser.
As with creating and updating cookies, deleting a cookie via setcookie() doesn ’ t delete it from the
$_COOKIE array while the script is running. However, the next time the browser visits the page, it will no
longer send the cookie to the server and the corresponding $_COOKIE array element will not be created.
277
9/21/09 9:05:11 AM
c10.indd 277
c10.indd 277 9/21/09 9:05:11 AM