Académique Documents
Professionnel Documents
Culture Documents
PHP
MostofthisisfromthePHPmanual
onlineat:
http://www.php.net/manual/
Ashorthistoryofphp
Parsing
Variables
Arrays
Operators
Functions
ControlStructures
ExternalDataFiles
Background
PHPisserversidescriptingsystem
PHPstandsfor"PHP:HypertextPreprocessor"
SyntaxbasedonPerl,Java,andC
Verygoodforcreatingdynamiccontent
Powerful,butsomewhatrisky!
Ifyouwanttofocusononesystemfordynamic
content,thisisagoodonetochoose
History
StartedasaPerlhackin1994byRasmusLerdorf
(tohandlehisresume),developedtoPHP/FI2.0
By1997uptoPHP3.0withanewparserengine
byZeevSuraskiandAndiGutmans
Version5.2.4iscurrentversion,rewrittenbyZend
(www.zend.com)toincludeanumberoffeatures,
suchasanobjectmodel
Currentisversion5
phpisoneofthepremierexamplesofwhatan
opensourceprojectcanbe
About Zend
ACommercialEnterprise
ZendprovidesZendengineforPHPforfree
Theyprovideotherproductsandservicesforafee
Serversidecachingandotheroptimizations
EncodinginZend'sintermediateformattoprotect
sourcecode
IDEadeveloper'spackagewithtoolstomakelifeeasier
Supportandtrainingservices
Zend'swebsiteisagreatresource
PHP 5 Architecture
Zendengineasparser(AndiGutmansandZeevSuraski)
SAPIisawebserverabstractionlayer
PHPcomponentsnowselfcontained(ODBC,Java,LDAP,
etc.)
Thisstructureisagoodgeneraldesignforsoftware
(comparetoOSImodel,andmiddlewareapplications)
imagefromhttp://www.zend.com/zend/art/intro.php
PHP Scripts
Typicallyfileendsin.phpthisissetbytheweb
serverconfiguration
Separatedinfileswiththe<?php?>tag
phpcommandscanmakeupanentirefile,orcanbe
containedinhtmlthisisachoice.
Programlinesendin";"oryougetanerror
Serverrecognizesembeddedscriptandexecutes
Resultispassedtobrowser,sourceisn'tvisible
<P>
<?php$myvar="HelloWorld!";
echo$myvar;
?>
</P>
Parsing
We'vetalkabouthowthebrowsercanreadatext
fileandprocessit,that'sabasicparsingmethod
Parsinginvolvesactingonrelevantportionsofa
fileandignoringothers
Browsersparsewebpagesastheyload
Webserverswithserversidetechnologieslikephp
parsewebpagesastheyarebeingpassedoutto
thebrowser
Parsingdoesrepresentwork,sothereisacost
Two Ways
Youcanembedsectionsofphpinsidehtml:
<BODY>
<P>
<?php$myvar="HelloWorld!";
echo$myvar;
</BODY>
Oryoucancallhtmlfromphp:
<?php
echo"<html><head><title>Howdy</title>
?>
Variables
Typedbycontext(butonecanforcetype),soit's
loose
Beginwith"$"(unlikejavascript!)
Assignedbyvalue
$foo="Bob";$bar=$foo;
Assignedbyreference,thislinksvars
$bar=&$foo;
Somearepreassigned,serverandenvvars
Forexample,therearePHPvars,eg.PHP_SELF,
HTTP_GET_VARS
00
phpinfo()
Thephpinfo()functionshowsthephp
environment
Usethistoreadsystemandservervariables,
settingstoredinphp.ini,versions,and
modules
Noticethatmanyofthesedataareinarrays
Thisisthefirstscriptyoushouldwrite
00_phpinfo.php
Variable Variables
Usingthevalueofavariableasthenameof
asecondvariable)
$a="hello";
$$a="world";
Thus:
echo"$a${$a}";
Isthesameas:
echo"$a$hello";
But$$aechoesas"$hello".
00_hello_world.php
Operators
Arithmetic(+,,*,/,%)andString(.)
Assignment(=)andcombinedassignment
$a=3;
$a+=5;//sets$ato8;
$b="Hello";
$b.="There!";//sets$bto"HelloThere!";
Bitwise(&,|,^,~,<<,>>)
$a^$b(Xor:Bitsthataresetin$aor$bbutnot
bothareset.)
~$a(Not:Bitsthataresetin$aarenotset,
andviceversa.)
Comparison(==,===,!=,!==,<,>,<=,>=)
Coercion
Justlikejavascript,phpislooselytyped
Coercionoccursthesameway
Ifyouconcatenateanumberandstring,the
numberbecomesastring
17_coercion.php
Whenthisprecedesacommand,errorsgeneratedareignored
(allowscustommessages)
Execution(`issimilartotheshell_exec()
function)
Youcanpassastringtotheshellforexecution:
$output = `ls -al`;
$output = shell_exec("ls -al");
Thisisonereasontobecarefulaboutusersetvariables!
Incrementing/Decrementing
++$a(Incrementsbyone,thenreturns$a.)
$a++(Returns$a,thenincrements$abyone.)
$a (Decrements$abyone,thenreturns$a.)
$a (Returns$a,thendecrements$abyone.)
And
Or
Xor
!$a
$a&&$b
$a||$b
Not
And
Or
Trueifboth$aand$baretrue.
Trueifeither$aor$bistrue.
Trueifeither$aor$bistrue,
butnotboth.
Trueif$aisnottrue.
Trueifboth$aand$baretrue.
Trueifeither$aor$bistrue.
Thetwoandsandorshavedifferent
precedencerules,"and"and"or"arelower
precedencethan"&&"and"||"
Useparenthesestoresolveprecedence
problemsorjusttobeclearer
Control Structures
WideVarietyavailable
if,else,elseif
while,dowhile
for,foreach
break,continue,switch
require,include,require_once,include_once
Control Structures
Mostlyparalleltowhatwe'vecovered
alreadyinjavascript
if,elseif,else,while,for,foreach,breakand
continue
Switch
Switch,whichwe'veseen,isveryuseful
Thesetwodothesame
switch($i){
things.
case0:
if($i==0){
echo"iequals0";
}elseif($i==1){
echo"iequals1";
}elseif($i==2){
echo"iequals2";
}
echo"iequals0";
break;
case1:
echo"iequals1";
break;
case2:
echo"iequals2";
break;
}
examplefromhttp://us3.php.net/manual/en/controlstructures.switch.php
Nesting Files
require(),include(),include_once(),require_once()are
usedtobringinanexternalfile
Thisletsyouusethesamechunkofcodeinanumber
ofpages,orreadotherkindsoffilesintoyourprogram
BeVERYcarefulofusingtheseanywhereclosetouser
inputifahackercanspecifythefiletobeincluded,
thatfilewillexecutewithinyourscript,withwhatever
rightsyourscripthas(readfileisagoodalternativeif
youjustwantthefile,butdon'tneedtoexecuteit)
Yes,Virginia,remotefilescanbespecified
Arrays
Youcancreateanarraywiththearrayfunction,orusetheexplodefunction(thisisveryusefulwhenreading
filesintowebprograms)
$my_array=array(1,2,3,4,5);
$pizza="piece1piece2piece3piece4piece5piece6";
$pieces=explode("",$pizza);
Anarrayissimplyavariablerepresentingakeyedlist
Alistofvaluesorvariables
Ifavariable,thatvarcanalsobeanarray
Eachvariableinthelisthasakey
Thekeycanbeanumberoratextlabel
Arrays
Arraysarelists,orlistsoflists,orlistoflistsof
lists,yougettheideaArrayscanbemulti
dimensional
Arrayelementscanbeaddressedbyeitherby
numberorbyname(strings)
Ifyouwanttoseethestructureofanarray,usethe
print_rfunctiontorecursivelyprintanarrayinside
ofpretags
Walking Arrays
Usealoop,egaforeachlooptowalkthrough
anarray
whileloopsalsoworkforarrayswith
numerickeysjustsetavariablefortheloop,
andmakesuretoincrementthatvariable
withintheloop
$colors=array('red','blue','green','yellow');
foreach($colorsas$color){
echo"Doyoulike$color?\n";
}
05_arrays.php
05_arrays.php
Youcan'techoan
arraydirectly
Youcanwalkthrough
anechoorprint()line
byline
Youcanuseprint_r(),
thiswillshowyouthe
structureofcomplex
arraysthatoutputis
totheright,andit's
handyforlearningthe
structureofanarray
Array
(
[1] => Array
(
[sku] => A13412
[quantity] => 10
[item] => Whirly
[price] => .50
)
Multidimensional Arrays
Aonedimensionalarrayisalist,aspreadsheetorothercolumnardata
istwodimensional
Basically,youcanmakeanarrayofarrays
$multiD = array
(
"fruits" => array("myfavorite" => "orange", "yuck" =>
"banana", "yum" => "apple"),
"numbers" => array(1, 2, 3, 4, 5, 6),
"holes"
=> array("first", 5 => "second", "third")
);
Thestructurecanbebuiltarraybyarray,ordeclaredwithasingle
statement
Youcanreferenceindividualelementsbynesting:
01a_arrays.php
print_r()willshowtheentirestructure,butdontforgetthepretags
The Surface
Thepowerofphpliespartiallyinthewealthof
functionsforexample,the40+arrayfunctions
array_flip()swapskeysforvalues
array_count_values()returnsanassociativearrayofall
valuesinanarray,andtheirfrequency
array_rand()pullsarandomelement
array_unique()removesduppies
array_walk()appliesauserdefinedfunctiontoeach
elementofanarray(soyoucandiceallofadataset)
count()returnsthenumberofelementsinanarray
array_search()returnsthekeyforthefirstmatchinan
array
08_array_fu.php
$items=file("./mydata.txt");
foreach ($items as $line)
{
$line = str_replace("\n", "",
$line);
$line = explode("\t", $line);
// do something with $line
str_replace()
trim(),ltrim(),rtrim()
implode(),explode()
addslashes(),stripslashes()
htmlentities(),html_entity_decode(),
htmlspecialchars()
striptags()
06_more_arrays.php
Thisisasimplescripttoreadandprocessatext
file
Thedatafileistabdelimitedandhasthecolumn
titlesasthefirstlineofthefile
How it works
Thescriptusesthefirstlinetobuildtextlabelsfor
thesubsequentlines,sothatthearrayelements
canbecalledbythetextlabel
Ifyouaddanewcolumn,thisscript
compensates
Textbasedarraysarenotpositiondependent
Thisscriptcouldbethebasisofanicefunction
Therearetwoversionofthis,callingtwodifferent
datafiles,butthat'stheonlydifference
06a_more_arrays.php
Thisversionshowshowtodynamicallybuildatableinthe
htmloutput
Alternative syntax
Appliestoif,while,for,foreach,andswitch
Changetheopeningbracetoacolon
Changetheclosingbracetoanendxxx
<?php
statement
if($a==5):
echo"aequals5";
echo"...";
<?phpif($a==5):?>
else:
Aisequalto5
echo"aisnot5";
<?phpendif;?>
endif;
?>
07
samplecodefromhttp://us3.php.net/manual/en/controlstructures.alternativesyntax.php
Sources
http://www.zend.com/zend/art/intro.php
http://www.php.net/
http://hotwired.lycos.com/webmonkey/prog
ramming/php/index.html