Using Cookies to Save Data in PHP

(0 votes, average 0 out of 5)

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:

$expireTime = 60 * 60 * 24 + time();  // 1 day
setcookie("myCookie", "hello,world", $expireTime);

 

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);
}
Partner Links:
 
Related Articles

» PHP Parse Error: Unexpected $

ErrorA PHP parse error returns, citing an "unexpected $".  Because this is a parse error, the PHP script does not run to any extent.SolutionThis error almost always results in a missing bracket somewhere.  Check your code carefully for missing brackets.  Using a PHP IDE can be useful for checking brackets that are not closed.  Brackets that span multiple PHP sections can be the trickiest to miss.  For instance:12345678910<?php$x = 3;if($x == 3){?> <a...

» Access Windows Files From within a Ubuntu (Wubi) Install

So maybe you have just installed Ubuntu through the Wubi installation or have been using Ubuntu through Wubi for a while, but you find yourself trying to get access to your Window's documents/music/videos/etcetera from Ubuntu and your not sure where to look.  Well, the solution is pretty simple but not very intuitive for most users. Follow these instructions to get access to the files contained within your Windows installation:Assuming your using Ubuntu 10.xx, go to the top left:...

» How to Send Mail in PHP

The BasicsPHP provides a handy function for mailing from a server.  On a basic level, all you need to do is call the function mail with three parameters, which has the following syntax.bool (string $to, string $subject, string $message [, string $headers][, string $additonal_params]]) These parameters are pretty straight forward.  Below is an example of how to send a very simple email message with no headers.1234$to = "example@wisc.edu";$subject = "This is an example email.";$message...