You are on page 1of 40

Introduction to php

PHP

MostofthisisfromthePHPmanual
onlineat:
http://www.php.net/manual/

What we'll cover

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>

?>

What do we know already?


Muchofwhatwelearnedaboutjavascript
holdstrueinphp(butnotall!),andother
languagesaswell
$name="bil";
echo"Howdy,mynameis$name";
echo"Whatwill$namebeinthisline?";
echo'Whatwill$namebeinthisline?';
echo'What'swrongwiththisline?';
if($name=="bil")
{
//Hey,what'sthis?
echo"gotamatch!";

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

Operators: The Movie


ErrorControl(@)

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.)

Son of the Valley of Operators


Logical
$aand$b
$aor$b
$axor$b

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

Example: A Dynamic Table


Ihatewritinghtmltables
Youcanbuildoneinphp
Thisexampleusespicturesandbuildsa
tablewithpicturesinonecolumn,and
captionsinanother
Thecaptionsaredrawnfromtextfiles
I'musingtables,butyoucouldusecssfor
placementeasily

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

Text versus Keys


Textkeysworklikenumberkeys(well,
really,it'stheotherwayaroundnumber
keysarejustlabels)
Youassignandcallthemthesameway,
exceptyouhavetoassignthelabeltothe
valueorvariables,eg:
echo"$my_text_array[third]";

$my_text_array = array(first=>1, second=>2, third=


echo "<pre>";
print_r($my_text_array);
echo "</pre>";

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
)

[2] => Array


(
[sku] => A43214
[quantity] => 14
[item] => Widget
[price] => .05
)

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:

echo "<p>Yes, we have no " . $multiD["fruits"]["yuck"] . "


(ok by me).</p>";

01a_arrays.php
print_r()willshowtheentirestructure,butdontforgetthepretags

Getting Data into arrays


Youcandirectlyreaddataintoindividual
arrayslotsviaadirectassignment:
$pieces[5]="pouletresistance";
Fromafile:
Usethefilecommandtoreadadelimitedfile
(thedelimitercanbeanyuniquechar):
$pizza=file(./our_pizzas.txt)
Useexplodetocreateanarrayfromaline
withinaloop:
$pieces=explode("",$pizza);

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

Using External Data


Youcanbuilddynamicpageswithjustthe
informationinaphpscript
Butwherephpshinesisinbuildingpages
outofexternaldatasources,sothattheweb
pageschangewhenthedatadoes
Mostofthetime,peoplethinkofadatabase
likeMySQLasthebackend,butyoucan
alsousetextorotherfiles,LDAP,pretty
muchanything.

Standard data files


Normallyyou'duseatabdelimitedfile,butyoucan
useprettymuchanythingasadelimiter
Filesgetreadasarrays,onelineperslot
Remembereachlineendsin\n,youshouldclean
thisup,andbecarefulaboutwhitespace
Oncethefileisread,youcanuseexplodetobreak
thelinesintofields,oneatatime,inaloop.

Standard data files


Youcanusetrim()tocleanwhitespaceand
returnsinsteadofstr_replace()
Noticethatthisisbuildinganarrayofarrays

$items=file("./mydata.txt");
foreach ($items as $line)
{
$line = str_replace("\n", "",
$line);
$line = explode("\t", $line);
// do something with $line

Useful string functions

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