PHP Cookies Example



PHP Cookies Example

In previous php tutorial we understood what is cookies and how to create, retrieve and destroy cookies in php.
Now, in this php tutorial we will take php form example for more understand about create cookies and delete cookies.

PHP cookies example

Here, we design php form with three textbox for name, age and city with three buttons for create cookies, retrieve cookies and delete cookies.

First, we enter some values in textbox for name, age and city then click create cookie button the cookies created on client computer. After creating cookies we retrieve cookies by clicking retrieve cookie button, when we click retrieve cookies button so all the values for name, age and city will be displayed on php form using echo statement. Then after click delete cookie button for delete cookies from users computer, After call delete button when we try to retrieve cookies values through retrieve cookie button, it will so the error message like “cookies deleted !!”.

The PHP form design code for cookies example.

<?php
if(isset($_POST["Submit1"]))
{
setcookie("name",$_POST["name"], time() + 3600, "/", "", 0);
setcookie("age", $_POST["age"], time() + 3600, "/", "", 0);
setcookie("city", $_POST["city"], time() + 3600, "/", "", 0);
echo "Cookies Created !!";
}

if(isset($_POST["Submit3"]))
{
setcookie("name","", time() - 3600, "/", "", 0);
setcookie("age", "", time() - 3600, "/", "", 0);
setcookie("city", "", time() - 3600, "/", "", 0);
} 
?>

<html>
<head>
<title>PHP Cookies Example</title>
</head>
<body>

<FORM method="POST" action="firstexample.php">

Enter Name : <input type="text" name="name"> <br/>
Enter Age : <input type="text" name="age"> <br/>
Enter City : <input type="text" name="city"> <br/>
<br/>
<input type="submit" name="Submit1" value="Create Cookie">
<input type="submit" name="Submit2" value="Retrive Cookie">
<input type="submit" name="Submit3" value="Delete Cookie">
</FORM>

<?php
if(isset($_POST['Submit2']))
{
if(isset($_COOKIE["name"]))
{
echo "Name = ". $_COOKIE["name"]."<br/>";
echo "Age = ". $_COOKIE["age"]."<br/>";
echo "City = ". $_COOKIE["city"]."<br/>";
}
else
{
echo "Cookies deleted !!";

}
}
?>

</body>
</html>

When run above code the out put should be like :

PHP cookies example
PHP Cookies Example for create, retrieve and delete cookies.

 

Leave a Reply

Your email address will not be published. Required fields are marked *