Cookies in PHP

Spread the love

What are Cookies?

Cookies in PHP are small text files which are saved by a browser in your computer. Cookies contain small pieces of data sent by the server, which can be accessed in any script.

Cookies are just like PHP variables except that cookies contain that data even after you turn off the computer or close your browser. But you can delete the cookie whenever you want.

What cookies stores?

Data in a cookie stored just like a normal variable. Every cookie variable has a name. We can store data in that named cookie variable. It also contains the expiration date. When the expiration date arrives the data in cookie variable gets destroyed. The expiration date is optional.

Setting/ creating Cookies in PHP:

setcookie():

PHP is having the setcookie() function to create a new cookie variable. This function is used to set the cookie variable values and an optional expiration date.

Syntax: setcookie(‘cookie_name’,’cookie_value’, <expiration_date>);

 

Accessing cookie values in PHP:

You can access cookie variable using $_COOKIE superglobal variable.

Example: setcookie(‘username’, ‘sam’);

In above example, the first argument “username” is a variable name or name of the cookie and second argument “sam” is the value of the cookie. To access value of “username” stored in cookie variable on any page in your application, you can use $_COOKIE[‘username’];

Example: echo “Last user visit with username – “.$_COOKIE[‘username’];

 

Deleting Cookies:

You cannot directly delete the cookie variable using any function. To delete cookie variable you have to set the expiration date of cookie. The cookie will automatically get deleted or expire at that particular date.

Example: setcookie(‘username’,’sam’,time()+(60*60*8);

In above example:

time() – is a function which will return current time.
first 60 – is seconds
second 60 – is minutes and
8 – is hours.
so time() + (60*60*8) =  8 hours.

Hence the cookie will get deleted automatically after 8 hours in future.

Deleting cookies manually:

If you want to delete cookie at any point of execution by yourself, you can do this by setting expiration date to the past time.

Example: setcookie(‘username’,’sam’,time() – 3600);

time() – 3600 – 1 hour in the past.

Whenever you execute above example your cookies deleted at that point.


Spread the love

Leave a Comment