How to Set Cookies in PHP
To Set cookies using PHP, setcookie() function is used. Cookie is a piece of information that stored in the client’s machine (usually browser) by the server.
setcookie() contains 6 parameters
- Name of the cookie- usage- “FirstCookie”
- The value of the cookie. This value is stored on the clients computer; do not store sensitive information. Assuming the name is ‘Iamthecookie’, this value is retrieved through $_COOKIE['Iamthecookie']
- Expiration time of a cookie- usage – time()+60 //means that current time + 60 seconds,
- The path on the server in which the cookie will be available on. If set to ‘/’, the cookie will be available within the entire domain . If set to ‘/osp/’, the cookie will only be available within the /osp/ directory and all sub-directories such as /osp/bar/ of domain . The default value is the current directory that the cookie is being set in.
- The domain that the cookie is available. To make the cookie available on all subdomains of example.com then you’d set it to ‘.example.com’. The . is not required but makes it compatible with more browsers. Setting it to www.example.com will make the cookie only available in the www subdomain.
- Indicates that the cookie should only be transmitted over a secure HTTPS connection from the client. When set to , the cookie will only be set if a secure connection exists. The default is 0. On the server-side, it’s on the programmer to send this kind of cookie only on secure connection.
$c=setcookie(”name”,”Iamthecookie”,time()+100, “/”,”.eadhoc.com”, 0);
echo “The cookie set successfully”;
echo “Cookies may be disabled or not set”;
The above script sets a cookie of name ‘name’ and value being ‘Iamthecookie’ which will be available for 100 seconds, and it is for the entire server eadhoc.com and it is not secure (as it uses 0 – HTTP)
to delete the above said cookie,
change the code to
echo “The cookie deleted successfully”;
echo “Something Wrong”;