Cookies in php

Cookies in php, infact in all lnguages,are used to identify the user.

A cookie is a file that server saves on the user computer. Whenever the same computer request the server for any webpage it sends cookies too with the request. Cookies are not secure method to identify the user because it saves on the user's computer and there can be security issues.

Creating Cookies:-

The setcookie() function in php is used to create the cookies. This function must come at the top of your webpage before the opening tag of html.

Example of Creating Cookies:-

setcookie("programmer","Adeel Fakhar",time+3600);

The above example is creating a cookie with name programmer, setting its value Adeel Fakhar and expiration time is after one hour.

You can set expiration time through variable too, like below

$expiration_time=time()+60*60*24*20;

setcookie("programmer","Adeel Fakhar", $expiration_time);

In the above example, the expiration time is set to after 20 days

How to retrieve value from Cookies?

$_COOKIE is used to retrieve the value of the cookie.

for above example, to retrieve value from programmer cookie, just use this

$_COOKIE["programmer"];

to view all cookies just type

print_r($_COOKIE);

Deleting Cookies

To delete the cookie just set its expiration time to the past. Like in the below example we are setting expiration time of cookie one hour ago

cookie("programmer","Adeel Fakhar",time()-3600);

What to do, if browser is not supporting Cookies?

If your application is dealing with browsers that are not supporting cookies then your website is useless for the users because in the middle all functionality of your website will collapse, so try to use sessions or sent data through forms using get or post method. This is professional way.



0 comments: