Conmanly cookies are used to store the information of a web page in a client computer browser, that cookies use or help when the same user comes back to that page, that information can be retrieved from the browser itself and take less time to reload page.
Note:Each time the browser requests a page to the server, all the data in the cookie is automatically sent to the server within the request.
setcookie(name, value, expire, path, domain, secure);
The parameters of the setcookie() function have the following meanings:
Parameter | Description |
---|---|
name | The name of the cookie. |
value | The value of the cookie. Do not store sensitive information since this value is stored on the user’s computer. |
expires | The expiry date in UNIX timestamp format. After this time cookie will become inaccessible. The default value is 0 . |
path | Specify the path on the server for which the cookie will be available. If set to '/' , the cookie will be available within the entire domain. |
domain | Specify the domain for which the cookie is available to e.g www.example.com. |
secure | This field, if present, indicates that the cookie should be sent only if a secure HTTPS connection exists. |
Following example shows how to create a cookie in PHP.
In this example first parameter sets the name of the cookie as ‘phpkida’, the second parameter sets the value as ‘phpkida is a website’, the third parameter states that the cookie will be expired after 3600 seconds (note the way it has been declared, we use time() and then add the number of seconds we wish the cookie must be expired after), the fourth parameter sets path on the server ‘/home/your_name’ where your_name may be an username, so it directs the home directory of a user, the fifth and sixth parameter is set to 1, i.e. true, so the cookie is available over secure connections only and it is available on HTTP protocol only. echo $_COOKIE[“phpkida”]; simply prints the cookie value. This way you can retrieve cookie value.
<?php setcookie("phpkida", "phpkida is a website", time()+3600, "/home/your_usename/", "phpkida.com", 1, 1); if (isset($_COOKIE['cookie'])) echo $_COOKIE["phpkida"]; ?>