Cookies are created in PHP using the setcookie() function. setcookie() takes a number of arguments. The first argument is the name of the cookie (the name part of the name/value pair described earlier). The second is the value part of the name/value pair. |
The third argument is the optional expiration date of the cookie. The fourth argument specifies the active path for the cookie. The fifth argument is the domain setting and the sixth is the security setting (0 specifies HTTP and HTTPS and 1 specifies HTTPS only). |
Creating Cookie in PHP |
Based on the above information we can create a cookie using the following PHP: |
<?php setcookie(‘username’, ‘Ruchita’, time() + 4800); echo ‘Cookie has been set<br>’; ?> |
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=Ruchita’. The cookie will expire 4800 seconds from the time it is created. |
Reading a Cookie in PHP |
Given 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 tutorial). |
For example we can obtain the value of our userName cookie as follows: |
<?php echo ‘Reading cookie<br>’; echo ‘userName = ‘ . $_COOKIE[‘userName’]; ?> |
The above script should generate the following output: |
Cookie has been set Reading cookie userName = Ruchita |
Deleting a Cookie |
Cookies are deleted by calling the setcookie() function with the cookie name, a null for the value and an expiration date in the past. Once again the time() function can be used to calculate an expired date: |
<?php setcookie (‘userName’, ”, time() – 4800); ?> |
Note that if you specified domain and/or path arguments when you created the cookie you must also specify them when you delete the cookie. |