PHP code of setting and reading cookies of different kinds
Posted On at by milanSETTING COOKIES
In PHP we can set different kind of cookies lets see how.
1. A simple cookie which only have a name and a value
setcookie("CookieNameHere",$value);
Variable $value here may contain any string value
2. A cookie with a name, a value and expire time
setcookie("CookieNameHere",$value,time()+3600);
This cookie is the same like first one but the difference is it will expire after given time. Here time() shows current time(In seconds from 1970) and 3600 are seconds which added to current time so cookie will expire in next hour. You can give give a time in way that cookie expire in next three days but always it must be current time using time() plus number of seconds.
I have given time()+3600 for hour as it has 3600 seconds I can also give it like time()+60*60 or for three days it will be time()+60*60*24*3. Here 60*60*24*3 is the equivalent of three days in seconds.
After cookie is expired you can't read its value anymore.
3. A cookie with a name, value, expire time and path
setcookie("CookieNameHere",$value,time()+3600,"/");
Here fourth argument to cookie which is '/' is path and will set the cookie which will be valid for whole site. As '/' denotes the root directory so any file at site can access it.
If I don't give a path cookie will only be set for all files in current or its sub directories so files in other directories can't read it.
Also path Can be specified like "../folder1/subfolder" so only files in "../folder1/subfolder" will be able to read it.
READING COOKIES
It is very simple.
for printing it.
for assigning its value to other variable.