mit 6.470, iap 2010 yafim landa ([email protected])6.470.scripts.mit.edu/2010/lectures/php/php.pdf ·...

20
PHP MIT 6.470, IAP 2010 Yafim Landa ([email protected])

Upload: others

Post on 17-Mar-2021

0 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: MIT 6.470, IAP 2010 Yafim Landa (landa@mit.edu)6.470.scripts.mit.edu/2010/lectures/php/php.pdf · 2011. 10. 17. · LAMP • We’ll use Linux, Apache, MySQL, and PHP for this course

PHP

MIT6.470,IAP2010YafimLanda([email protected])

Page 2: MIT 6.470, IAP 2010 Yafim Landa (landa@mit.edu)6.470.scripts.mit.edu/2010/lectures/php/php.pdf · 2011. 10. 17. · LAMP • We’ll use Linux, Apache, MySQL, and PHP for this course

LAMP

• We’lluseLinux,Apache,MySQL,andPHPforthiscourse

•  Therearealternatives– WindowswithIISandASP– JavawithTomcat

– OtherdatabasesystemslikePostgreSQL,ornon‐SQLdatabases

Page 3: MIT 6.470, IAP 2010 Yafim Landa (landa@mit.edu)6.470.scripts.mit.edu/2010/lectures/php/php.pdf · 2011. 10. 17. · LAMP • We’ll use Linux, Apache, MySQL, and PHP for this course

WhyPHP?

•  Averysimpleandstraightforwardsyntax–  PHPisreallywelldocumented:http://php.net/–  Typethenameofafunctionyouwanttolookupattheendofthe

URL,andyou’llbesentdirectlytotherelevanthelppage,forexample:http://php.net/json_encode

•  TightintegrationwithMySQL(andlotsofotherdatabasesystems)•  Wellestablishedandcreatedspecificallyfortheweb

–  UsedbyFacebook,Wikipedia,YouTube,Digg,andplentyofothers•  Doeslotsofcoolthingslikeencryption,imagemanipulation,email,

fileupload,andsoonwithease•  ObjectorientedasofPHP5:http://php.net/manual/en/

language.oop5.php•  Convenienttypesystemfortheweb

Page 4: MIT 6.470, IAP 2010 Yafim Landa (landa@mit.edu)6.470.scripts.mit.edu/2010/lectures/php/php.pdf · 2011. 10. 17. · LAMP • We’ll use Linux, Apache, MySQL, and PHP for this course

WhatDoesPHPDo?

•  Generatespagesthattheusercansee– Retrievesanyinformationfromthedatabaseorfromothersources

– DisplaysanHTMLpagewithdynamiccontent

– Writesdatabacktothedatabaseorperformsotheroperations

•  GeneratesdataforyourAJAXrequests

Page 5: MIT 6.470, IAP 2010 Yafim Landa (landa@mit.edu)6.470.scripts.mit.edu/2010/lectures/php/php.pdf · 2011. 10. 17. · LAMP • We’ll use Linux, Apache, MySQL, and PHP for this course

•  RegularHTMLpagescanchangeonlythroughtheuseofJavascript– Verysuperficial(withouttheuseofAJAX)

•  HTMLcanberendereddynamicallyusingPHP– Thepagecanchangedependingonthetimeofday,thecontentsofthedatabase,theuser’sinput,etc.

Page 6: MIT 6.470, IAP 2010 Yafim Landa (landa@mit.edu)6.470.scripts.mit.edu/2010/lectures/php/php.pdf · 2011. 10. 17. · LAMP • We’ll use Linux, Apache, MySQL, and PHP for this course

• WealreadyknowhowtomakeHTMLpagesthatshowstaticcontent

•  Toadddynamiccontent,wecansimplyembedPHPcodewithinanHTMLpageusingaspecialtag

•  ThisembeddedcodeisexecutedontheserverbeforeitissenttotheclientandlookslikeregularHTMLtotheclient

Page 7: MIT 6.470, IAP 2010 Yafim Landa (landa@mit.edu)6.470.scripts.mit.edu/2010/lectures/php/php.pdf · 2011. 10. 17. · LAMP • We’ll use Linux, Apache, MySQL, and PHP for this course
Page 8: MIT 6.470, IAP 2010 Yafim Landa (landa@mit.edu)6.470.scripts.mit.edu/2010/lectures/php/php.pdf · 2011. 10. 17. · LAMP • We’ll use Linux, Apache, MySQL, and PHP for this course

LanguageSyntax

•  http://6.470.scripts.mit.edu/2009/•  Doublequotesvs.singlequotes

–  If$var issetto“6.470”•  echo “This is $var” willoutputThisis6.470•  echo ‘This is $var’ willoutputThisis$var

•  Associativearrays– $var [‘foo’] = ‘hello, world’; – foreach ($var as $key => $value) {

•  $var isan(associative)array•  Makes$key (akey)and$value (thevaluestoredatthatkey)availableoneachloopiteration

•  ===doesacomparisonwithtype•  http://www.php.net/manual/en/langref.php

Page 9: MIT 6.470, IAP 2010 Yafim Landa (landa@mit.edu)6.470.scripts.mit.edu/2010/lectures/php/php.pdf · 2011. 10. 17. · LAMP • We’ll use Linux, Apache, MySQL, and PHP for this course

Superglobals

•  PHPhasseveralspecialvariablesthatareglobaleverywhere

•  Alloftheseareassociativearrays– $_SERVER–serverandexecutionenvironmentinformation

•  $_SERVER[‘PHP_SELF’]isusefulfortheformactionattribute

– $_GET–variablespassedthroughtheURL•  http://some.server.com/index.php?param=value

– $_POST–variablespassedthroughtheHTTPPOSTmethod– $_REQUEST–bothGETandPOSTcombined– $_FILES–filesuploadedthroughHTTPPOST– $_COOKIE–contentsofHTTPcookies– $_SESSION–anassociativearrayofsessionvariables

Page 10: MIT 6.470, IAP 2010 Yafim Landa (landa@mit.edu)6.470.scripts.mit.edu/2010/lectures/php/php.pdf · 2011. 10. 17. · LAMP • We’ll use Linux, Apache, MySQL, and PHP for this course

ErrorHandling

•  Todebugyourcode,insertthefollowingtwolinesatthebeginningofyourscript:

ini_set('display_errors',1);

error_reporting(E_ALL);

Page 11: MIT 6.470, IAP 2010 Yafim Landa (landa@mit.edu)6.470.scripts.mit.edu/2010/lectures/php/php.pdf · 2011. 10. 17. · LAMP • We’ll use Linux, Apache, MySQL, and PHP for this course

Example:Firstdynamiccontent

•  Demo:http://landa.scripts.mit.edu/6.470/examples/example1/index.php

•  Code:http://landa.scripts.mit.edu/6.470/examples/example1/code.html

Page 12: MIT 6.470, IAP 2010 Yafim Landa (landa@mit.edu)6.470.scripts.mit.edu/2010/lectures/php/php.pdf · 2011. 10. 17. · LAMP • We’ll use Linux, Apache, MySQL, and PHP for this course

Example:Superglobals

•  Demo:http://landa.scripts.mit.edu/6.470/examples/example2/index.php

•  Code:http://landa.scripts.mit.edu/6.470/examples/example2/code.html

Page 13: MIT 6.470, IAP 2010 Yafim Landa (landa@mit.edu)6.470.scripts.mit.edu/2010/lectures/php/php.pdf · 2011. 10. 17. · LAMP • We’ll use Linux, Apache, MySQL, and PHP for this course

Input

• Wecangetinputfromvarioussources– GETandPOSTrequestvariables,fromtheuser

•  Includesinputfromforms• Accessusing$_GET,$_POST,or$_REQUESTsuperglobalassociativearrays

– Fileuploadsfromtheuser– Changingdatainthedatabase– OtherwebsitesandAPIs

• Twitter,Google,Facebook,andsoon

Page 14: MIT 6.470, IAP 2010 Yafim Landa (landa@mit.edu)6.470.scripts.mit.edu/2010/lectures/php/php.pdf · 2011. 10. 17. · LAMP • We’ll use Linux, Apache, MySQL, and PHP for this course

WorkingWithMySQL

•  Putthedatabaseconnectioncodeinaseparatefile(database.php)

•  include_once ‘database.php’

Page 15: MIT 6.470, IAP 2010 Yafim Landa (landa@mit.edu)6.470.scripts.mit.edu/2010/lectures/php/php.pdf · 2011. 10. 17. · LAMP • We’ll use Linux, Apache, MySQL, and PHP for this course

•  $sql = mysql_query($query) – $query istheMySQLquerystring(like“SELECT*FROMcomments”)

– Returnsaresourceandstoresitin$sql– Youcanstepovertherowsintheresourceonebyonebywriting

$row = mysql_fetch_object($sql) or $row = mysql_fetch_array($sql)– Oftenusedinawhileloop

•  while($row = mysql_fetch_array($sql)) { •  Loopsuntilalloftherowshavebeenexamined

– Seecomments.phpinFeedbackexample

Page 16: MIT 6.470, IAP 2010 Yafim Landa (landa@mit.edu)6.470.scripts.mit.edu/2010/lectures/php/php.pdf · 2011. 10. 17. · LAMP • We’ll use Linux, Apache, MySQL, and PHP for this course

SessionManagement(LoggingIn)

•  SessionsallowyoutostoredatathatpersistsbetweenPHPpages– Thismeansthatwecancreateanaccountsystem

•  Storetheuser’saccountdatainsessions– Using$_SESSIONsuperglobal

• Mustcallsession_start() atthebeginningofeachpagetousesessions

Page 17: MIT 6.470, IAP 2010 Yafim Landa (landa@mit.edu)6.470.scripts.mit.edu/2010/lectures/php/php.pdf · 2011. 10. 17. · LAMP • We’ll use Linux, Apache, MySQL, and PHP for this course

Example:Feedback

•  http://landa.scripts.mit.edu/6.470/feedback/index.php

•  Topics– Sessions

• MITcertificates

– WorkingwithMySQL– $_POST

Page 18: MIT 6.470, IAP 2010 Yafim Landa (landa@mit.edu)6.470.scripts.mit.edu/2010/lectures/php/php.pdf · 2011. 10. 17. · LAMP • We’ll use Linux, Apache, MySQL, and PHP for this course

Example:OutputtingJSON

•  http://landa.scripts.mit.edu/6.470/feedback/comments.php?limit=10

•  UsefulforfeedingdatatoAJAXcalls•  Topics

– Usealimitusing$_GET[‘limit’]–  EnablingJSONusingphp.ini–  Errorreporting

•  DisplaysallofthecommentsinthedatabaseinJSONformat–  ExaminetheJSONoutputusinghttp://jsonformatter.curiousconcept.com/

Page 19: MIT 6.470, IAP 2010 Yafim Landa (landa@mit.edu)6.470.scripts.mit.edu/2010/lectures/php/php.pdf · 2011. 10. 17. · LAMP • We’ll use Linux, Apache, MySQL, and PHP for this course

DateandTimeFunctions

•  TheeasiestthingtodoistoconverteverythingintoandworkwithsecondssinceJanuary1,1970

•  date($format [, $timestamp]) formatsthetimestamp(usedtodisplaythedateinahuman

readableformat)•  time() getsthecurrenttimemeasuredinsecondssinceJanuary

1,1970•  strtotime($time [, $now]) convertsastringlike“next

Monday”intosecondssinceJanuary1,1970•  UseMySQL’sfunctionsFROM_UNIXTIME and

UNIX_TIMESTAMP toconvertbetweenPHPandMySQLdateformats

•  http://us.php.net/manual/en/ref.datetime.php

Page 20: MIT 6.470, IAP 2010 Yafim Landa (landa@mit.edu)6.470.scripts.mit.edu/2010/lectures/php/php.pdf · 2011. 10. 17. · LAMP • We’ll use Linux, Apache, MySQL, and PHP for this course

InputFiltering•  It’susuallybestnottotrustexternaldata

– Caninvokevariousvulnerabilities,HTMLcode,andotherthingsthatyoumaynotwant

•  Asafirstlineofdefenseyoushould– strip_tags($input) toremoveHTMLtags– addslashes($input) beforewritingdatatothedatabaseandstripslashes($input) afterretrievingitback

– mysql_real_escape_string($input) forSQLqueries

•  Moreaboutthistomorrow