Java Techies- Solution for All
Cookies
- Cookies are small text files that are used by a Web server to keep track of users.
- A cookie has value in the form of name-value pairs.
- Getting a cookie means using the name to retrieve the value.
Create a Cookie
setCookie()
:This function is used to set a cookie.Syntax :
setcookie(name, value, expire, path, domain);
Argument | Type | Description |
---|---|---|
name | string | Name of Cookie. |
value | string | Value to store in cookie |
expire | int | Specifies the duration when this cookie should expire. |
path | string | page within the Web root folder would see this named cookie |
domain | string | no check is made against the domain requested by the client. |
secure | int (0 or 1) | If it is 1,the cookie will only be sent over a secure socket layer or default to set 0. |
Example :
<?php setcookie("user", "techknowheights", time()+3600); ?>
Note: In above example cookie name is user,value is tecknowheights,cookie should expire after 1 hour.
Retrieve a Cookie Value
A variable
$_COOKIE
is used to retrieve a cookie value.
Example :
<?php setcookie("user", "techknowheights", time()+3600); ?> <?php echo $_COOKIE["user"]; // view only one cookie echo "<br>"; print_r($_COOKIE); //to view all cookies ?>
Output :
techknowheights Array ( [user] => techknowheights )
Delete the Cookie
It is very easy to delete the cookie and should give expiration date in the past.
Example :
<?php setcookie("user", "", time()-3600); ?>