1
IT350: Web & Internet Programming
Set 15: Cookies
Information Example
https://www.usna.edu/Users/cs/adina/teaching/it350/fall2016/solutions/cookies/info.html (“info” link on today’s calendar)
Information Example - - PDF document
IT350: Web & Internet Programming Set 15: Cookies Information Example https://www.usna.edu/Users/cs/adina/teaching/it350/fall2016/solutions/cookies/info.html (info link on todays calendar) How does the second page know what you
https://www.usna.edu/Users/cs/adina/teaching/it350/fall2016/solutions/cookies/info.html (“info” link on today’s calendar)
function createCookie(identifier, value, days) { if( days ) { var date = new Date(); date.setTime( date.getTime()+(days*24*60*60*1000) ); var expires = "; expires=“ + date.toGMTString(); } else var expires = ""; document.cookie = identifier + "=“ + escape(value) + expires; } function eraseCookie(identifier) { createCookie(identifier, "", -1); }
// Return the 'value' of the cookie with identifier 'desiredId' // returns null if no match found. function readCookie(desiredId) { // First split the pairs apart on '; ' var pairs = document.cookie.split("; "); // Now split each pair on '='. Check if have a match for (var i=0; i < pairs.length; i++) { var aPair = pairs[i]; // split into desired parts and check for match var cookieTokens = aPair.split("="); var id = cookieTokens[0]; var value = cookieTokens[1]; if (id == desiredId) { // found desired cookie -- return value return unescape(value); } } return null; // no match }
<?php require('page.inc.php'); $name = $_POST["name"]; $height = $_POST["height"]; $color = $_POST["color"]; $expires = time() + 86400; setcookie("Name",$name,$expires); setcookie("Height",$height,$expires); setcookie("Color",$color,$expires); $page = new Page("Storing Cookies"); $page->content = "<h1>A cookie was stored!</h1>"; $page->content .= "<h2>Name: $name <br> Height: $height <br> Color: $color</h2>"; $page->display(); ?>
<?php require("page.inc.php"); $page = new Page("Reading cookies"); $name=""; $height = ""; $color = ""; if (isset($_COOKIE["Name"])) $name = $_COOKIE["Name"]; $height = $_COOKIE["Height"]; $color = $_COOKIE["Color"]; if (!empty($name) && !empty($height) && !empty($color)) { $page->content = "<h1>Some cookies were found!</h1>"; $page->content .="<h2>Name: $name</h2>"; $page->content .="<h2>Height: $height</h2>"; $page->content .="<h2>Color: $color</h2>"; } else{ $page->content ="<h1>Could not find cookies for Name, Height,
} $page->display();?>
When PHP is called, look for a “sessionID” cookie. If present, print “Welcome back” (in HTML). If the cookie doesn’t exist, create a random ID and set the cookie. Print “Welcome visitor!”
a)Create a cookie called “favQuote” with value “DTT/FSA”. b)Then change your program to instead use the quote provided by the user through a form submission with param name “quote”.