Join us Now |  Forgot Password? | Forgot UserName?


Learn step by step

PHP Cookies

In web programming, the term 'cookie' means something totally different from what it is popularly known as. In web programming, a 'cookie' is a small text file stored on a users hard drive by a website for various purposes such as remembering a user who frequents that website.

Setting a cookie

Setting a cookie with PHP could not be easier, since PHP provides a function for you to do precisely that. The following code sets a cookie called "userlogin" with a value of "anonymous"

$date_of_expiry = time() + 60 ;
setcookie( "userlogin", "anonymous", $date_of_expiry );

The code starts by calculating the expiry date of the cookie. Cookies have a limited lifespan. If you do not set an expiry date, the cookie will expire automatically when the user closes his/her web browser. The expiry date has to be in a special format, so it's actually simplest to just use the time() function and work from there. This function returns the current date and time in the required format. My code adds 60 seconds to the existing time, effectively making the cookie last for only 1 minute. The second line calls the setcookie() function, which does the actual work of setting the cookie in PHP. This is a built-in function in PHP. The first parameter (or argument) to setcookie() is the name that you want to give the cookie. It can be any name you like. In the example above, I gave the cookie the name "userlogin". The second parameter to the setcookie() function contains the actual data that you want saved. Again, this can be any data you like, although the maximum size of any cookie is 4 KB. This 4 KB includes things like the date of expiry, the name, and other cookie overheads, so you don't really have all 4,096 bytes to work with. Note that cookies are not encrypted by default, so unless you encrypt your data yourself, you should not store any sensitive information in them.

Delete a Cookie

Cookies can also be deleted. This is useful for situations such as when a user logs out of your site. To delete a cookie, call the setcookie() function again with the same name, folder and domain that you used earlier to set the cookie. However, instead of an expiry date set in the future, this time give an expiry date some time in the past.

$date_of_expiry = time() - 60 ;
setcookie( "userlogin", "anonymous", $date_of_expiry, "/",
"example.com" );

Related Videos