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à
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:
3. Theformcodewilllooklikethis:
continuedonnextpageà
File3.Formhandlerforaddinganewuser.
1. CreateaPHPfile.Saveitasnewuser.php.Putthefollowingcodeinthefile:
File4.Loginaregistereduser.1. CreateanewPHPfile.Saveitassession.php.(Thefilenamelogin.phpisalreadyinuse.)
File5.Seewhoisloggedin.
1. CreateanewPHPfile.Saveitascontinue.php.
continuedonnextpageà
File6.Logoutanddeletethesession.
1. CreateanewPHPfile.Saveitaslogout.php.
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à
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.
Top Related