PHP COOKIES
1.Cookies is a client-side temporary memory storage
2. It stores the data usually in the browser and it is mostly used to find the user.
3.Sometimes the user visits the page at a certain time after few minutes or hours later the user wants to give the request to the browser the cookie also goes for the request in the backend.
1.Cookies is a client-side temporary memory storage
2. It stores the data usually in the browser and it is mostly used to find the user.
3.Sometimes the user visits the page at a certain time after few minutes or hours later the user wants to give the request to the browser the cookie also goes for the request in the backend.
Create a cookie:
The following syntax will show the cookie creation syntax.
syntax:
setcookie(name,value,expire,path,domain);
Example:
<?php
setcookie("agent", "shaun marsh",time( ) +3600);
?>
In the above example, the name is assigned an agent and the value is Shaun Marsh.And also the cookie specifies it will expire one hour.
<?php
$cookie_name ="agent";
$cookie_value="Ricky Ponting";
setcookie($cookie_name,$cookie_value,time() + (172800 * 30),"/"); // 172800 = 2 days
?>
<html>
</body>
<?php
if(!isset($_COOKIE[$cookie_name])
{
echo "cookie named '" . $cookie_name . "' is not set!";
}
else
{
echo "cookie '" .$cokie_name. "' is set!<br>";
echo "Value is:" . $_COOKIE [$cookie_name];
}
}
?>
</body>
</html>
output:
Cookie 'agent' is set!
value is: Ricky Ponting
Example:
<?php
setcookie("agent", "shaun marsh",time( ) +3600);
?>
In the above example, the name is assigned an agent and the value is Shaun Marsh.And also the cookie specifies it will expire one hour.
PHP Cookie retrieve:
In this section, we see the how cookie variables are retrieved.We retrieve the value of the cookie "agent" by $_COOKIE
Example:
$cookie_name ="agent";
$cookie_value="Ricky Ponting";
setcookie($cookie_name,$cookie_value,time() + (172800 * 30),"/"); // 172800 = 2 days
?>
<html>
</body>
<?php
if(!isset($_COOKIE[$cookie_name])
{
echo "cookie named '" . $cookie_name . "' is not set!";
}
else
{
echo "cookie '" .$cokie_name. "' is set!<br>";
echo "Value is:" . $_COOKIE [$cookie_name];
}
}
?>
</body>
</html>
output:
Cookie 'agent' is set!
value is: Ricky Ponting
Delete a cookie:
In this section, we see how to delete a cookie in PHP programming language.
Example:
<?php
// set the expiration date to two hour ago
setcookie ("agent", "",time () - 7200);
?>
<html>
<body>
<?php
echo "Cookie'agent' is deleted.";
</body>
</html>
output:
Cookie 'agent' is deleted.
No comments:
Post a Comment