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

» Variables in PHP

A variable is a way to store information in may program and scripting languages. In PHP, variables can store things such as strings, integers, floats, boolean, or other objects.To definite and initialize a variable in PHP, you simply use the following form within your code: 1$variable_name = value;When creating a new variable in PHP, you must follow the simple naming conventions below:Variables must start with a letter or underscore ("_").Variables with more than one word should be...

» Setting ownership (chown) on an NTFS partition in Ubuntu with NTFS-3G

If you want to set ownership of a folder on an NTFS drive in Linux, you need to change the ownership of its entry in /etc/fstab. Unfortunately you cannot use chown because NTFS is not a POSIX-compatible filesystem. Open up Users and Groups and find your user's ID. The first user on an Ubuntu install has uid 1000. Similarly, click on Manage Groups and find your group - the gid for the first user is 1000. Open /etc/fstab as root sudo gedit /etc/fstab and change the mount line to include the uid...

» How to Determine Which Programs are Using Which Ports

Sometimes a program is using a particular port, preventing another program from capturing and using it. It can be difficult to trace down which process exactly is using the port. Fortunately, there are a couple helpful utilities which can link each process with the port(s) it is using.WindowsOn Windows, download and run . It will display a table of the currently running processes and the ports they are using. It is possible to sort by process name or the port number to make it easy to find the...