Lecture 5 - Cookies, sessions and file writing - annotated

Lecture 5 - Cookies, sessions and file writing - annotated...

Info icon This preview shows pages 1–3. Sign up to view the full content.

1 Cookies, Sessions, and Files INFO/COM S 230: Intermediate Web Design and Programming Cookies Cookies Cookies are one way to save limited amounts of information between visits of a user. Saving a cookie setcookie($name, $value) setcookie($name, $value, $expiration) Without $expiration argument, cookie goes away when the browser closes. $expiration is number of seconds after January 1, 1970. Set as follows: setcookie(“name”, “value”, time() + 60*60); Must be at the top of the .php file ( before the DOCTYPE or any other HTML). Getting a cookie If a cookie was set using setcookie(“name”, “value”), and the expiration date has not passed, then when the user returns, the variable $_COOKIE[“name”] will contain “value”. <?php if (!isset($_COOKIE["username"]) && isset($_POST["username"])) { setcookie("username",$_POST["username"], time()+60*60); } ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" " "> <html> <?php if (isset($_COOKIE["username"])) { print("<p>Welcome, ".$_COOKIE['username']."! </p>"); } elseif (isset($_POST["username"])) { print("<p>Welcome, ".$_POST['username']."! </p>"); } else { ?> <form method="post" action=“cookie-form.php"> <p>What is your name? <input type="text" name="username" /> </p> <input type="submit" value="Click to submit" /> </form> <?php } ?> Easy PDF Creator is professional software to create PDF. If you wish to remove this line, buy it now.
Image of page 1

Info icon This preview has intentionally blurred sections. Sign up to view the full version.