34,333
edits
Changes
→Creating a Cookie in PHP
<?php
setcookie('username', 'JohnW', time() + 4800);
echo 'Cookie has been set<br>';
?>
</pre>
The above example creates a cookie on the computer system of anyone who loads the page (assuming they have cookies enabled in their browser) containing the name value pair ''userName=JohnW'. The cookie will expire 4800 seconds from the time it is created.
== Reading a Cookie ==
Gven that you've gone to the trouble of writing a cookie it stands to reason you'll probably want to read it back at some point. This is achieved by accessing the $_COOKIE array. The $_COOKIE array is an associative array whereby the name of the cookie provides the index into the array to extract the corresponding value of the name/value pair (for details of PHP arrays read the [[PHP Arrays]] chapter of this book.
For example we can obtain the value of our ''userName'' cookie as follows:
<pre
<?php
setcookie('userName', 'JohnW', time() + 4800);
echo 'Cookie has been set<br>';
echo 'Reading cookie<br>';
echo 'userName = ' . $_COOKIE['userName'];
?>
</pre>
The above script should generate the following output:
<tt>
Cookie has been set<br>
Reading cookie<br>
userName = JohnW<br>
</tt>