Cookies are a useful way to save information, for example a user preference or login session locally on the client's machine. PHP makes creating and accessing cookies very easy. To create a cookie called myCookie with the value hello,world, simply add the following line of PHP code:
This data will then be available the next time the user loads that particular page. To access the cookie at a later date, use the global $_COOKIE variable:
1 2 3 4 5 |
if ($_COOKIE["myCookie"] == "hello,world") { // some code here } else { // other code here } |
It is also useful to check and see if a user has the cookie saved at all before trying to query it. To do this, use the isset function to test whether or not the variable is defined:
1 2 3 4 5 6 |
if (isset($_COOKIE["myCookie"])) { // the cookie exists already, use it } else { // the cookie doesn't exist, create it setcookie("myCookie", "hello,world", $expireTime); } |




