In: Computer Science
Modify the code so that it provides a web form to collect the cookie values from the users. In other words, you will add two text boxes where users will enter the cookie name and the cookie value. You will also add a submit button, which lets users to send the cookie values to the server. The page should display the previous cookie values when it is loaded.
<!DOCTYPE html>
<?php
$cookie_name = "user";
$cookie_value = "John Doe";
setcookie($cookie_name, $cookie_value, time() +
(86400 * 30), "/"); // 86400 = 1 day
?>
<html>
<body>
<?php
if(!isset($_COOKIE[$cookie_name])) {
echo "Cookie named '" . $cookie_name . "' is not
set!";
} else {
echo "Cookie '" . $cookie_name . "' is
set!<br>";
echo "Value is: " . $_COOKIE[$cookie_name];
}
?>
<p><strong>Note:</strong> You might have to
reload the page to see the value of the cookie.</p>
</body>
</html>
Code:
<!DOCTYPE html>
<?php
//check wheathe submit button is clicked or not. if clicked then it will set cookie name and value
if (isset($_POST['name'])){
$cookie_name = $_POST['name'];
$cookie_value = $_POST['value'];
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day
}
?>
<html>
<body>
<!--here is the form to set cookie name and value manually-->
<form action="index.php" method="post">
<p>Cookie name: <input type="text" name="name" /></p>
<p>Cookie value: <input type="text" name="value" /></p>
<p><input type="submit" name="Submit"/></p>
</form>
<?php
if(isset($cookie_name)) {
//it display cookie name and value if cookie set
if(!isset($_COOKIE[$cookie_name])) {
echo "To see previous cookie reload the page.";
} else {
echo "Cookie '" . $cookie_name . "' is set!<br>";
echo "Value is: " . $_COOKIE[$cookie_name];
}
}else{
echo "No any previous cookies";
}
?>
<p><strong>Note:</strong> You might have to reload the page to see the value of the cookie.</p>
</body>
</html>
Output:
After clicking submit button.
After refreshing a page.