php homework week 14 chapter 12 cookies sessions...php homework for week 14 · chapter 12 · cookies...

9
PHP Homework for Week 14 · Chapter 12 · Cookies and Sessions Exercise 1. Cookies. The textbook tells you about cookies but does not really give you much sample code. This is the simplest possible set of pages that will let you communicate between two pages using a cookie. File 1. Form. 1. Create a folder and call it Chapter12. Your work will go in this folder. 2. Create an HTML/PHP file. Save it as setcookie.php. This will be an all-in-one form that has the form handler within the form. The form handler just sets a cookie. 3. The form also has an option to log the user out, which deletes the cookie. Note that both buttons have the name of submit but they have different values. 4. Put this code in setcookie.php: continued on next page à

Upload: others

Post on 03-Aug-2020

7 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: PHP Homework Week 14 Chapter 12 Cookies Sessions...PHP Homework for Week 14 · Chapter 12 · Cookies and Sessions Exercise 1. Cookies. The textbook tells you about cookies but does

PHPHomeworkforWeek14·Chapter12·CookiesandSessions

Exercise1.Cookies.

Thetextbooktellsyouaboutcookiesbutdoesnotreallygiveyoumuchsamplecode.Thisisthesimplestpossiblesetofpagesthatwillletyoucommunicatebetweentwopagesusingacookie.

File1.Form.1. CreateafolderandcallitChapter12.Yourworkwillgointhisfolder.2. CreateanHTML/PHPfile.Saveitassetcookie.php.Thiswillbeanall-in-oneformthathas

theformhandlerwithintheform.Theformhandlerjustsetsacookie.3. Theformalsohasanoptiontologtheuserout,whichdeletesthecookie.Notethatboth

buttonshavethenameofsubmitbuttheyhavedifferentvalues.4. Putthiscodeinsetcookie.php:

continuedonnextpageà

Page 2: PHP Homework Week 14 Chapter 12 Cookies Sessions...PHP Homework for Week 14 · Chapter 12 · Cookies and Sessions Exercise 1. Cookies. The textbook tells you about cookies but does

File2.Seethecookie.1. CreateanHTML/PHPfile.Saveitasgetcookie.php.2. Putthiscodeinthegetcookie.phpfile.Thiscodereadsthecookieanddisplaysitsvalue.

Exercise2.Sessions.

Thetextbookhassomesamplecodeforsessions.Ihadaproblemwiththeirsamplecode.Theauthenticationcodedoesnotwork.Anyway,thecodemaybealittleoverlycomplicated.Icreatedasystemthatperformsasimilarfunctionwithoutdoingtheencryption.Thisway,youcanseethesessioncodewithoutgettingittangledupwiththeencryptioncode.IreplacedtheHTTPauthenticationwithanHTMLformthatchecksitsvaluesagainstaMySQLdatabase.

Thetextbook’sauthenticationmechanism,whichusesHTTPauthentication,isnotusedverymuch.Oneproblemisthatonceloggedin,itisnotpossibletologbackoutandloginagainasanewuser.Soitisdifficulttotesttheauthenticationcodetomakesureitwon’tauthenticateabadusername/passwordcombination.

File1.Logincredentials.

1. Putyourlogin.phpfilefromlastThursdaynight(orseetextbookpage234)inaplacewhereyoucanincludeit,eitherintherootlevelofyourwebsite(htdocs,www,orpublic_html)orintheChapter12folder.

File2.Formforaddinganewuser.

1. CreateanHTMLfile.Callitnewuser.html.ItwillhaveonlyHTMLcode.2. Theformwilllooklikethis:

Page 3: PHP Homework Week 14 Chapter 12 Cookies Sessions...PHP Homework for Week 14 · Chapter 12 · Cookies and Sessions Exercise 1. Cookies. The textbook tells you about cookies but does

3. Theformcodewilllooklikethis:

continuedonnextpageà

Page 4: PHP Homework Week 14 Chapter 12 Cookies Sessions...PHP Homework for Week 14 · Chapter 12 · Cookies and Sessions Exercise 1. Cookies. The textbook tells you about cookies but does

File3.Formhandlerforaddinganewuser.

1. CreateaPHPfile.Saveitasnewuser.php.Putthefollowingcodeinthefile:

Page 5: PHP Homework Week 14 Chapter 12 Cookies Sessions...PHP Homework for Week 14 · Chapter 12 · Cookies and Sessions Exercise 1. Cookies. The textbook tells you about cookies but does

File4.Loginaregistereduser.1. CreateanewPHPfile.Saveitassession.php.(Thefilenamelogin.phpisalreadyinuse.)

Page 6: PHP Homework Week 14 Chapter 12 Cookies Sessions...PHP Homework for Week 14 · Chapter 12 · Cookies and Sessions Exercise 1. Cookies. The textbook tells you about cookies but does

File5.Seewhoisloggedin.

1. CreateanewPHPfile.Saveitascontinue.php.

continuedonnextpageà

Page 7: PHP Homework Week 14 Chapter 12 Cookies Sessions...PHP Homework for Week 14 · Chapter 12 · Cookies and Sessions Exercise 1. Cookies. The textbook tells you about cookies but does

File6.Logoutanddeletethesession.

1. CreateanewPHPfile.Saveitaslogout.php.

Page 8: PHP Homework Week 14 Chapter 12 Cookies Sessions...PHP Homework for Week 14 · Chapter 12 · Cookies and Sessions Exercise 1. Cookies. The textbook tells you about cookies but does

Exercise3.Useacookieonavisitcounter.

1. Objective:addavisitorcounterinaMySQLdatabase.Updatethevisitorcounteronlyfornewvisitorsbysettingacookiethefirsttimetheyvisit.Createaninterfacefordeletingthecookiesowecantestthecookiemechanism.DisplaythevisitorcountinthefooterofyourProject.

2. CreateaMySQLtableforstoringthevisitorcount.CREATE TABLE counter (id INT NOT NULL PRIMARY KEY, counter INT); INSERT INTO counter VALUES (1, 0);

3. InyourProject,addthiscodeinheaders.phptoupdatethevisitorcounterwheneversomeonevisitsanypageonyoursite:<?php require_once('login.php'); $conn = new mysqli($hn, $un, $pw, $db); if ($conn->connect_error) die($conn->connect_error); if (empty ($_COOKIE['visited'])) { $query = "UPDATE counter SET counter=counter+1 WHERE id=1"; $result = $conn->query($query); $query = "SELECT counter FROM counter WHERE id=1"; $result = $conn->query($query); $result->data_seek(0); $row = $result->fetch_array(MYSQLI_ASSOC); $visitors = $row['counter']; setcookie ("visited", $visitors, time()+(60*60*24)); } else { $visitors = $_COOKIE['visited']; } ?>

4. NotethattheabovecookiecodemustappearbeforeanyHTMLcodethatmightbeprintedwithinyourPHPfile.TheremustnotbeevenasinglespacebeforetheaboveblockofPHPcode.

5. Inyourproject’sfooter.phpfile,addthisPHPcode:<?php echo "<p>Total visitors to this site: $visitors </p>\n"; ?>

continuedonnextpageà

Page 9: PHP Homework Week 14 Chapter 12 Cookies Sessions...PHP Homework for Week 14 · Chapter 12 · Cookies and Sessions Exercise 1. Cookies. The textbook tells you about cookies but does

6. CreateanewfileforyourProjectcalledstate.php(ifyouhaven’tdonesoalready).

7. Linkthestate.phpfiletothebuttonsthatsayStateInformation.

8. Inthestate.phpfile,givesomeinformationaboutstatemechanisms,andprovidealinkorbuttonwheretheusercandeletethecookie.Youcanseeanexampleofthiswebpagehere:

http://php.missioncollege.edu/~markb/project/state.php

9. Thelinkorbuttonforremovingthecookieshouldlinktoafilethatyoumightcall

removecookie.phpordeletecookie.php.Itshouldhavecodelikethis,whichremovesthecookieatthetopofthefile,thenincludesalltheotherheadersandnavigationthatareapartofyourtemplate.Providealinkbacktothestate.phppage.

<?php setcookie('visited', '', time() - 1000000, "/"); ?> <?php include "header.php"; ?> <div id='content'> <h1>PHP Class Project</h1> <div id='textnav'> <?php include "textnav.php"; ?> </div> <div id='buttonnav'> <?php include "buttonnav.php"; ?> </div> <div id='main'> <h2>State Information</h2> <p>Cookie deleted</p> <a href='state.php'>Back</a> </div> <!-- main --> </div> <!-- content --> <?php include "footer.php"; ?>

10. Notethatthecodeforremovingacookieinvolvessettingittoanemptystringwithanexpirationdate

inthepast.Thisisjustsamplecodethatfitsmytemplate.Yourtemplatemaybedifferent. Exercise4.

LinkallthesefilestoyourhomepagesoIcanlookatthemquickly.