MIT 6.470, IAP 2010 Yafim Landa (landa@mit.edu)6.470.scripts.mit.edu/2010/lectures/php/php.pdf ·...

Preview:

Citation preview

PHP

MIT6.470,IAP2010YafimLanda(landa@mit.edu)

LAMP

• We’lluseLinux,Apache,MySQL,andPHPforthiscourse

•  Therearealternatives– WindowswithIISandASP– JavawithTomcat

– OtherdatabasesystemslikePostgreSQL,ornon‐SQLdatabases

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

WhatDoesPHPDo?

•  Generatespagesthattheusercansee– Retrievesanyinformationfromthedatabaseorfromothersources

– DisplaysanHTMLpagewithdynamiccontent

– Writesdatabacktothedatabaseorperformsotheroperations

•  GeneratesdataforyourAJAXrequests

•  RegularHTMLpagescanchangeonlythroughtheuseofJavascript– Verysuperficial(withouttheuseofAJAX)

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

• WealreadyknowhowtomakeHTMLpagesthatshowstaticcontent

•  Toadddynamiccontent,wecansimplyembedPHPcodewithinanHTMLpageusingaspecialtag

•  ThisembeddedcodeisexecutedontheserverbeforeitissenttotheclientandlookslikeregularHTMLtotheclient

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

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

ErrorHandling

•  Todebugyourcode,insertthefollowingtwolinesatthebeginningofyourscript:

ini_set('display_errors',1);

error_reporting(E_ALL);

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

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

Input

• Wecangetinputfromvarioussources– GETandPOSTrequestvariables,fromtheuser

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

– Fileuploadsfromtheuser– Changingdatainthedatabase– OtherwebsitesandAPIs

• Twitter,Google,Facebook,andsoon

WorkingWithMySQL

•  Putthedatabaseconnectioncodeinaseparatefile(database.php)

•  include_once ‘database.php’

•  $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

SessionManagement(LoggingIn)

•  SessionsallowyoutostoredatathatpersistsbetweenPHPpages– Thismeansthatwecancreateanaccountsystem

•  Storetheuser’saccountdatainsessions– Using$_SESSIONsuperglobal

• Mustcallsession_start() atthebeginningofeachpagetousesessions

Example:Feedback

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

•  Topics– Sessions

• MITcertificates

– WorkingwithMySQL– $_POST

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/

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

InputFiltering•  It’susuallybestnottotrustexternaldata

– Caninvokevariousvulnerabilities,HTMLcode,andotherthingsthatyoumaynotwant

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

– mysql_real_escape_string($input) forSQLqueries

•  Moreaboutthistomorrow