Php w3 School

download Php w3 School

of 129

Transcript of Php w3 School

  • 8/19/2019 Php w3 School

    1/129

    PHP 5 Tutorial (HOME) http://www.w3schools.com/php/php_includes.asp

    !3"chools Home  #e$t %hapter &

    PHP is a ser'er scriptin lanuae and is a power*ul tool *or ma+in d,namic and interacti'e

    !e- paes uic+l,.

    PHP is a widel,used *ree and e**icient alternati'e to competitors such as Microso*t0s 1"P.

    Eas, 2earnin with "how PHP

    Our "how PHP tool ma+es it eas, to learn PHP it shows -oth the PHP source code and theHTM2 output o* the code.

    E$ample

    46O%T7PE html8

    4html84-od,8

    49phpecho M, *irst PHP script98

    4/-od,84/html8 O/P M, *irst PHP script

    INTRO

    PHP scripts are e$ecuted on the ser'er.

    What You Should Already Know

    ;e*ore ,ou continue ,ou should ha'e a -asic understandin o* the *ollowin:

    • HTM2

    • %""

  • 8/19/2019 Php w3 School

    2/129

    • PHP is an acron,m *or PHP H,perte$t Preprocessor

    • PHP is a widel,used open source scriptin lanuae

    • PHP scripts are e$ecuted on the ser'er 

    • PHP costs nothin it is *ree to download and use

    PHP is an amazing and popular language!

    =t is power*ul enouh to -e at the core o* the -iest -loin s,stem on the we- (!ordPress)

    =t is deep enouh to run the larest social networ+ (?ace-oo+)

    =t is also eas, enouh to -e a -einner0s *irst ser'er side lanuae

    What is a PHP File?

    • PHP *iles can contain te$t HTM2 %""

  • 8/19/2019 Php w3 School

    3/129

    • PHP can encr,pt data

    !ith PHP ,ou are not limited to output HTM2. 7ou can output imaes P6? *iles and e'en

    ?lash mo'ies. 7ou can also output an, te$t such as @HTM2 and @M2.

    Why PHP?

    • PHP runs on 'arious plat*orms (!indows 2inu$ Ani$ Mac O" @ etc.)

    • PHP is compati-le with almost all ser'ers used toda, (1pache ==" etc.)

    • PHP supports a wide rane o* data-ases

    PHP is *ree. 6ownload it *rom the o**icial PHP resource: www.php.net

    • PHP is eas, to learn and runs e**icientl, on the ser'er side

    SYNTAX

    The PHP script is e$ecuted on the ser'er and the plain HTM2 result is sent -ac+ to the -rowser.

    ;asic PHP ",nta$

    1 PHP script can -e placed an,where in the document.

    1 PHP script starts with :

    49php// PHP code oes here98

    The de*ault *ile e$tension *or PHP *iles is .php.

    1 PHP *ile normall, contains HTM2 tas and some PHP scriptin code.

    ;elow we ha'e an e$ample o* a simple PHP *ile with a PHP script that uses a -uiltin PHP*unction echo to output the te$t Hello !orld on a we- pae:

    E$ample

    46O%T7PE html84html84-od,8

    http://www.php.net/http://www.php.net/

  • 8/19/2019 Php w3 School

    4/129

    4hB8M, *irst PHP pae4/hB8

    49phpecho Hello !orld

    98

    4/-od,84/html8

    Run eample

    No"e# PHP statements are terminated -, semicolon (). The closin ta o* a -loc+ o* PHP codealso automaticall, implies a semicolon (so ,ou do not ha'e to ha'e a semicolon terminatin thelast line o* a PHP -loc+).

    %omments in PHP

    1 comment in PHP code is a line that is not read/e$ecuted as part o* the proram. =ts onl, purpose is to -e read -, someone who is editin the code

    %omments are use*ul *or:

    • To let others understand what ,ou are doin %omments let other prorammers

    understand what ,ou were doin in each step (i* ,ou wor+ in a roup)

    • To remind ,oursel* what ,ou did Most prorammers ha'e e$perienced comin -ac+ to

    their own wor+ a ,ear or two later and ha'in to re*iure out what the, did. %ommentscan remind ,ou o* what ,ou were thin+in when ,ou wrote the code

    PHP supports three wa,s o* commentin:

    E$ample

    46O%T7PE html84html84-od,8

    49php// This is a sinle line comment

    C This is also a sinle line comment

    /DThis is a multiple lines comment -loc+ 

    http://www.w3schools.com/php/showphp.asp?filename=demo_syntaxhttp://www.w3schools.com/php/showphp.asp?filename=demo_syntax

  • 8/19/2019 Php w3 School

    5/129

    that spans o'er more thanone lineD/98

    4/-od,84/html8

    Run eample

    PHP %ase "ensiti'it,

    =n PHP all userde*ined *unctions classes and +e,words (e.. i* else while echo etc.) are #OTcasesensiti'e.

    =n the e$ample -elow all three echo statements -elow are leal (and eual):

    E$ample

    46O%T7PE html84html84-od,8

    49phpE%HO Hello !orld4-r8echo Hello !orld4-r8

    EcHo Hello !orld4-r898

    4/-od,84/html8

    Howe'er in PHP all 'aria-les are casesensiti'e.

    =n the e$ample -elow onl, the *irst statement will displa, the 'alue o* the color 'aria-le (this is -ecause color %O2OF and co2OF are treated as three di**erent 'aria-les):

    E$ample

    46O%T7PE html84html84-od,8

    49phpcolorGred

    http://www.w3schools.com/php/showphp.asp?filename=demo_syntax_commentshttp://www.w3schools.com/php/showphp.asp?filename=demo_syntax_comments

  • 8/19/2019 Php w3 School

    6/129

    echo M, car is . color . 4-r8echo M, house is . %O2OF . 4-r8echo M, -oat is . co2OF . 4-r898

    4/-od,84/html8$aria%les

    Variables are "containers" for storing information:

    Example

  • 8/19/2019 Php w3 School

    7/129

    0ules for ,-, 'ariables:

    • A 'ariable starts #ith the 1 sign* follo#e& by the name of the 'ariable

    • A 'ariable name must start #ith a letter or the un&erscore character

    • A 'ariable name cannot start #ith a number

    • A 'ariable name can only contain alpha2numeric characters an& un&erscores $A2* 324* an& / %

    • Variable names are case sensiti'e $1y an& 1 are t#o &ifferent 'ariables%

    0emember that ,-, 'ariable names are case2sensiti'e

    7reating $8eclaring% ,-, Variables

    ,-, has no comman& for &eclaring a 'ariable(

    A 'ariable is create& the moment you first assign a 'alue to it:

    Example

  • 8/19/2019 Php w3 School

    8/129

    ,-, automatically con'erts the 'ariable to the correct &ata type* &epen&ing on its'alue(

    n other languages such as 7* 7!!* an& ;a'a* the programmer must &eclare the namean& type of the 'ariable before using it(

    ,-, Variables lobal

  • 8/19/2019 Php w3 School

    9/129

    e%ho '

  • 8/19/2019 Php w3 School

    10/129

    ,-, also stores all global 'ariables in an array calle& 1>L?@AL

  • 8/19/2019 Php w3 School

    11/129

    .hen* each time the function is calle&* that 'ariable #ill still ha'e the information itcontaine& from the last time the function #as calle&(

    Note: .he 'ariable is still local to the function(

    &'ho and prin" s"a"emen"sn ,-, there are t#o basic #ays to get output: echo an& print(

    n this tutorial #e use echo $an& print% in almost e'ery example(

  • 8/19/2019 Php w3 School

    12/129

    .he follo#ing example sho#s ho# to &isplay strings an& 'ariables #ith the echocomman&:

    Example

  • 8/19/2019 Php w3 School

    13/129

    $%ars=array2'7ol5o'9'W'9'1oyota'3!

    print $txt)!print '*@8'!

    ?&

    Run example »

    (a"a ")pes

  • 8/19/2019 Php w3 School

    14/129

    • An integer can be either positi'e or negati'e

    • ntegers can be specifie& in three formats: &ecimal $+32base&%* hexa&ecimal$+62base& 2 prefixe& #ith 3x% or octal $G2base& 2 prefixe& #ith 3%

    n the follo#ing example #e #ill test &ifferent numbers( .he ,-, 'ar/&ump$% functionreturns the &ata type an& 'alue of 'ariables:

    Example

  • 8/19/2019 Php w3 School

    15/129

    ,-, @ooleans

    @ooleans can be either .0FE or )AL

  • 8/19/2019 Php w3 School

    16/129

  • 8/19/2019 Php w3 School

    17/129

    .he ,-, strlen$% function

    .he strlen$% function returns the length of a string* in characters(

    .he example belo# returns the length of the string "-ello #orl&":

    Example

  • 8/19/2019 Php w3 School

    18/129

    ip: .he position of the string "#orl&" in the example abo'e is 6( .he reason that it is 6$an& not I%* is that the first character position in the string is 3* an& not +(

    7omplete ,-,

  • 8/19/2019 Php w3 School

    19/129

  • 8/19/2019 Php w3 School

    20/129

    .he example belo# sho#s the &ifferent results of using the &ifferent arithmeticoperators:

    Example

  • 8/19/2019 Php w3 School

    21/129

    Example

  • 8/19/2019 Php w3 School

    22/129

  • 8/19/2019 Php w3 School

    23/129

    e%ho $i! ,, outputs ?&

    Run example »

    ,-, 7omparison ?perators

    .he ,-, comparison operators are use& to compare t#o 'alues $number or string%:

    &perator Name 'xample Result

    == Eual 1x == 1y .rue if 1x is eual to 1y

    === &entical 1x === 1y .rue if 1x is eual to 1y* an& ttype

    = Dot eual 1x = 1y .rue if 1x is not eual to 1y

    OP Dot eual 1x OP 1y .rue if 1x is not eual to 1y

    == Dot i&entical 1x == 1y .rue if 1x is not eual to 1y* o

    same type

    P >reater than 1x P 1y .rue if 1x is greater than 1y

    O Less than 1x O 1y .rue if 1x is less than 1y

    P= >reater than or eualto

    1x P= 1y .rue if 1x is greater than or e

    O= Less than or eual to 1x O= 1y .rue if 1x is less than or eua

    .he example belo# sho#s the &ifferent results of using some of the comparisonoperators:

    Example

  • 8/19/2019 Php w3 School

    24/129

    $y=')**'!

    5arGdu0p2$x == $y3!e%ho '

  • 8/19/2019 Php w3 School

    25/129

    ,-, Array ?perators

    .he ,-, array operators are use& to compare arrays:

    &perator Name 'xample Result

    ! Fnion 1x ! 1y Fnion of 1x an& 1y $but &uplicate keyo'er#ritten%

    == Euality 1x == 1y .rue if 1x an& 1y ha'e the same key'

    === &entity 1x === 1y .rue if 1x an& 1y ha'e the same key'same or&er an& of the same types

    = neuality 1x = 1y .rue if 1x is not eual to 1y

    OP neuality 1x OP 1y .rue if 1x is not eual to 1y

    == Don2i&entity 1x == 1y .rue if 1x is not i&entical to 1y

    .he example belo# sho#s the &ifferent results of using the &ifferent array operators:

    Example

  • 8/19/2019 Php w3 School

    26/129

    ,-, 7on&itional

  • 8/19/2019 Php w3 School

    27/129

    ,-, 2 .he if(((else

  • 8/19/2019 Php w3 School

    28/129

      code to be executed if condition is true;8 else 4

      code to be executed if condition is false;

    8

    .he example belo# #ill output "-a'e a goo& morning" if the current time is less than

    +3* an& "-a'e a goo& &ay" if the current time is less than H3( ?ther#ise it #ill output"-a'e a goo& night":

    Example

  • 8/19/2019 Php w3 School

    29/129

      code to be executed if n is dierent from all labels;8

    .his is ho# it #orks: )irst #e ha'e a single expression n $most often a 'ariable%* that ise'aluate& once( .he 'alue of the expression is then compare& #ith the 'alues for eachcase in the structure( f there is a match* the block of co&e associate& #ith that case is

    execute&( Fse brea* to pre'ent the co&e from running into the next case automatically(.he de)ault statement is use& if no match is foun&(

    Example

  • 8/19/2019 Php w3 School

    30/129

    • while 2 loops through a block of co&e as long as the specifie& con&ition is true

    • do...while 2 loops through a block of co&e once* an& then repeats the loop aslong as the specifie& con&ition is true

    )or 2 loops through a block of co&e a specifie& number of times

    • )oreach 2 loops through a block of co&e for each element in an array

    .he ,-, #hile Loop

    .he #hile loop executes a block of co&e as long as the specifie& con&ition is true(

    "yntaxwhile 2condition is true3 4  code to be executed!8

    .he example belo# first sets a 'ariable 1x to + $1x=+T%( .hen* the #hile loop #illcontinue to run as long as 1x is less than* or eual to 5( 1x #ill increase by + each timethe loop runs $1x!!T%:

    Example

  • 8/19/2019 Php w3 School

    31/129

    "yntaxdo 4  code to be executed;

    8 while 2condition is true3!

    .he example belo# first sets a 'ariable 1x to + $1x=+T%( .hen* the &o #hile loop #ill

    #rite some output* an& then increment the 'ariable 1x #ith +( .hen the con&ition ischecke& $is 1x less than* or eual to 5U%* an& the loop #ill continue to run as long as 1xis less than* or eual to 5:

    Example

  • 8/19/2019 Php w3 School

    32/129

    ,-, for loops execute a block of co&e a specifie& number of times(

    .he ,-, for Loop

    .he for loop is use& #hen you kno# in a&'ance ho# many times the script shoul& run(

    "yntax/or 2init counter; test counter; increment counter 3 4

      code to be executed;

    8

    ,arameters:

    • init counter : nitialie the loop counter 'alue

    • test counter : E'aluate& for each loop iteration( f it e'aluates to .0FE* the loopcontinues( f it e'aluates to )AL

  • 8/19/2019 Php w3 School

    33/129

    "yntax/orea%h 2$array as $value3 4

      code to be executed;

    8

    )or e'ery loop iteration* the 'alue of the current array element is assigne& to 1'alue

    an& the array pointer is mo'e& by one* until it reaches the last array element(

    .he follo#ing example &emonstrates a loop that #ill output the 'alues of the gi'enarray $1colors%:

    Example

  • 8/19/2019 Php w3 School

    34/129

    A user &efine& function &eclaration starts #ith the #or& "function":

    "yntax/un%tion functionName23 4  code to be executed!

    8

    Note: A function name can start #ith a letter or un&erscore $not a number%(

    ip: >i'e the function a name that reflects #hat the function &oes

    )unction names are D?. case2sensiti'e(

    n the example belo#* #e create a function name& "#riteMsg$%"( .he opening curlybrace $ % in&icates the beginning of the function co&e an& the closing curly brace $ W %

    in&icates the en& of the function( .he function outputs "-ello #orl&"( .o call thefunction* ust #rite its name:

    Example

  • 8/19/2019 Php w3 School

    35/129

    use& insi&e the function* #hich outputs se'eral &ifferent first names* but an eual lastname:

    Example

  • 8/19/2019 Php w3 School

    36/129

  • 8/19/2019 Php w3 School

    37/129

    e%ho 'B liRe ' + $%ars>*@ + '9 ' + $%ars>)@ + ' and ' + $%ars>@ + '+'!?&

    Run example »

    9hat is an ArrayUAn array is a special 'ariable* #hich can hol& more than one 'alue at a time(

    f you ha'e a list of items $a list of car names* for example%* storing the cars in single'ariables coul& look like this:

    $%ars)='7ol5o'!$%ars='W'!$%ars='1oyota'!

    -o#e'er* #hat if you #ant to loop through the cars an& fin& a specific oneU An& #hat ifyou ha& not J cars* but J33U

    .he solution is to create an array

    An array can hol& many 'alues un&er a single name* an& you can access the 'alues byreferring to an in&ex number(

    7reate an Array in ,-,

    n ,-,* the array$% function is use& to create an array:

    array23!

    n ,-,* there are three types of arrays:

    • +ndexed arrays 2 Arrays #ith a numeric in&ex

    • (ssociative arrays 2 Arrays #ith name& keys

    • ,ultidimensional arrays 2 Arrays containing one or more arrays

    ,-, n&exe& Arrays

    .here are t#o #ays to create in&exe& arrays:

    .he in&ex can be assigne& automatically $in&ex al#ays starts at 3%:

    http://www.w3schools.com/php/showphp.asp?filename=demo_array_numhttp://www.w3schools.com/php/showphp.asp?filename=demo_array_num

  • 8/19/2019 Php w3 School

    38/129

    $%ars=array2'7ol5o'9'W'9'1oyota'3!

    or the in&ex can be assigne& manually:

    $%ars>*@='7ol5o'!$%ars>)@='W'!

    $%ars>@='1oyota'!

    .he follo#ing example creates an in&exe& array name& 1cars* assigns three elementsto it* an& then prints a text containing the array 'alues:

    Example

  • 8/19/2019 Php w3 School

    39/129

      e%ho 'Peter@=''!$a-e>en@='J'!$a-e>oe@='I'!

    .he name& keys can then be use& in a script:

    Example

  • 8/19/2019 Php w3 School

    40/129

    Run example »

    Multi&imensional ArraysMulti&imensional arrays #ill be explaine& in the ,-, a&'ance& section(

    7omplete ,-, Array 0eference

    )or a complete reference of all array functions* go to our complete ,-, Array0eference(

    .he reference contains a brief &escription* an& examples of use* for each function

    Sorting arrays

    .he elements in an array can be sorte& in alphabetical or numerical or&er* &escen&ingor ascen&ing(

    ,-, 2

  • 8/19/2019 Php w3 School

    41/129

    Example

  • 8/19/2019 Php w3 School

    42/129

  • 8/19/2019 Php w3 School

    43/129

    Run example »

  • 8/19/2019 Php w3 School

    44/129

    • 1/0EFE

  • 8/19/2019 Php w3 School

    45/129

    ,-, 1/

  • 8/19/2019 Php w3 School

    46/129

    1/

  • 8/19/2019 Php w3 School

    47/129

  • 8/19/2019 Php w3 School

    48/129

    ,-, 1/>E.

    ,-, 1/>E. can also be use& to collect form &ata after submitting an -.ML form #ithmetho&="get"(

    1/>E. can also collect &ata sent in the F0L(

    Assume #e ha'e an -.ML page that contains a hyperlink #ith parameters:

  • 8/19/2019 Php w3 School

    49/129

    Example

  • 8/19/2019 Php w3 School

    50/129

  • 8/19/2019 Php w3 School

    51/129

    9hen to use >E.U

    nformation sent from a form #ith the >E. metho& is visible to everyone $all 'ariable

    names an& 'alues are &isplaye& in the F0L%( >E. also has limits on the amount ofinformation to sen&( .he limitation is about H333 characters( -o#e'er* because the'ariables are &isplaye& in the F0L* it is possible to bookmark the page( .his can beuseful in some cases(

    >E. may be use& for sen&ing non2sensiti'e &ata(

    Note: >E. shoul& DEVE0 be use& for sen&ing pass#or&s or other sensiti'e information

    9hen to use ,?

  • 8/19/2019 Php w3 School

    52/129

    .hese pages #ill sho# ho# to process ,-, forms #ith security in min&( ,roper 'ali&atioimportant to protect your form from hackers an& spammers

    .he -.ML form #e #ill be #orking at in these chapters* contains 'arious input fiel&s:reuire& an& optional text fiel&s* ra&io buttons* an& a submit button:

    .he 'ali&ation rules for the form abo'e are as follo#s:

    2ield $alidation Rules

    Dame 0euire&( ! Must only contain letters an& #hitespace

    E2mail 0euire&( ! Must contain a 'ali& email a&&ress $#ith Y an& (%

    9ebsite ?ptional( f present* it must contain a 'ali& F0L7omment ?ptional( Multi2line input fiel& $textarea%

    >en&er 0euire&( Must select one

    )irst #e #ill look at the plain -.ML co&e for the form:

    .ext )iel&s

    .he name* email* an& #ebsite fiel&s are text input elements* an& the comment fiel& is atextarea( .he -.ML co&e looks like this:

    Na0e6

  • 8/19/2019 Php w3 School

    53/129

    .he )orm Element

    .he -.ML co&e of the form looks like this:

  • 8/19/2019 Php w3 School

    54/129

  • 8/19/2019 Php w3 School

    55/129

    OscriptPlocation(href$Nhttp:###(hacke&(comN%OscriptP

    2 this #oul& not be execute&* because it #oul& be sa'e& as -.ML escape& co&e* likethis:

    RltTscriptRgtTlocation(href$Nhttp:###(hacke&(comN%RltTscriptRgtT

    .he co&e is no# safe to be &isplaye& on a page or insi&e an e2mail(

    9e #ill also &o t#o more things #hen the user submits the form:

    +(

  • 8/19/2019 Php w3 School

    56/129

    Dotice that at the start of the script* #e check #hether the form has been submitte&using 1/

  • 8/19/2019 Php w3 School

    57/129

  • 8/19/2019 Php w3 School

    58/129

    Example

  • 8/19/2019 Php w3 School

    59/129

      $na0err = 'nly letters and white spa%e allowed'!8

    he pre#match;< )unction searches a strin# )or patternB returnin# true i) the p

    and )alse otherwise.

    ,-, 2 Vali&ate E2mail

    .he easiest an& safest #ay to check #hether an email a&&ress is #ell2forme& is to use,-,Ns filter/'ar$% function(

    n the co&e belo#* if the e2mail a&&ress is not #ell2forme&* then store an errormessage:

    $e0ail = testGinput2$GPS1>'e0ail'@3!i/ 2(LlterG5ar2$e0ail9 FB;1MG7A;BDA1GAB;33 4  $e0ailrr = 'Bn5alid e0ail /or0at'!

    8

    ,-, 2 Vali&ate F0L

    .he co&e belo# sho#s a #ay to check if a F0L a&&ress syntax is 'ali& $this regularexpression also allo#s &ashes in the F0L%( f the F0L a&&ress syntax is not 'ali&* thenstore an error message:

    $we.site = testGinput2$GPS1>'we.site'@3!

    i/ 2(pre-G0at%h2',[.2?62?6https?\/tp36[,[,\www[+3>a#*EV][,?=^G\(69+!@O>a#*EV][,=^G\@,i'9$we.site33 4  $we.siterr = 'Bn5alid TM;'!

    8

    ,-, 2 Vali&ate Dame* E2mail* an& F0L

  • 8/19/2019 Php w3 School

    60/129

    Do#* the script looks like this:

    Example

  • 8/19/2019 Php w3 School

    61/129

      i/ 2e0pty2$GPS1>'-ender'@33 4  $-enderrr = ':ender is reXuired'!

      8 else 4  $-ender = testGinput2$GPS1>'-ender'@3!  8

    8?&

    Run example »

    .he next step is to sho# ho# to pre'ent the form from emptying all the input fiel&s#hen the user submits the form(

    "omplete form e#ample

    .his chapter sho# ho# to keep the 'alues in the input fiel&s #hen the user hits the

    submit button(

    ,-, 2 eep .he Values in .he )orm

    .o sho# the 'alues in the input fiel&s after the user hits the submit button* #e a&& alittle ,-, script insi&e the 'alue attribute of the follo#ing input fiel&s: name* email* an&#ebsite( n the comment textarea fiel&* #e put the script bet#een the OtextareaP an&OtextareaP tags( .he little script outputs the 'alue of the 1name* 1email* 1#ebsite*

    an& 1comment 'ariables(

    .hen* #e also nee& to sho# #hich ra&io button that #as checke&( )or this* #e mustmanipulate the checke& attribute $not the 'alue attribute for ra&io buttons%:

    Na0e6

  • 8/19/2019 Php w3 School

    62/129

  • 8/19/2019 Php w3 School

    63/129

    A t#o2&imensional array is an array of arrays $a three2&imensional array is an array ofarrays of arrays%(

    )irst* take a look at the follo#ing table:

    Name "toc* "oldVol'o HH +G

    @M9 +5 +J

  • 8/19/2019 Php w3 School

    64/129

      e%ho '

  • 8/19/2019 Php w3 School

    65/129

    -ere are some characters that are commonly use& for &ates:

    • & 2 0epresents the &ay of the month $3+ to J+%

    • m 2 0epresents a month $3+ to +H%

    • 2 0epresents a year $in four &igits%

    • l $lo#ercase NLN% 2 0epresents the &ay of the #eek

    ?ther characters* like""* "("* or "2" can also be inserte& bet#een the characters to a&&a&&itional formatting(

    .he example belo# formats to&ayNs &ate in three &ifferent #ays:

    Example

  • 8/19/2019 Php w3 School

    66/129

    -ere are some characters that is commonly use& for times:

    • h 2 +H2hour format of an hour #ith lea&ing eros $3+ to +H%

    • i 2 Minutes #ith lea&ing eros $33 to 54%

    • s 2

  • 8/19/2019 Php w3 School

    67/129

    Run example »

    7reate a 8ate 9ith ,-, mktime$%

    .he optional timestamp parameter in the &ate$% function specifies a timestamp( f you&o not specify a timestamp* the current &ate an& time #ill be use& $as sho#n in theexamples abo'e%(

    .he mktime$% function returns the Fnix timestamp for a &ate( .he Fnix timestampcontains the number of secon&s bet#een the Fnix Epoch $;anuary + +4I3 33:33:33>M.% an& the time specifie&(

    "yntax0Rti0e2hour,minute,second,month,day,year 3

    .he example belo# creates a &ate an& time from a number of parameters in themktime$% function:

    Example

  • 8/19/2019 Php w3 School

    68/129

  • 8/19/2019 Php w3 School

    69/129

    Run example »

    .he example belo# outputs the number of &ays until Xth of ;uly:

    Example

  • 8/19/2019 Php w3 School

    70/129

  • 8/19/2019 Php w3 School

    71/129

    'xample DAssume #e ha'e a stan&ar& menu file calle& "menu(php":

  • 8/19/2019 Php w3 School

    72/129

    Example

  • 8/19/2019 Php w3 School

    73/129

    Example

  • 8/19/2019 Php w3 School

    74/129

    .he rea&file$% function rea&s a file an& #rites it to the output buffer(

    Assume #e ha'e a text file calle& "#eb&ictionary(txt"* store& on the ser'er* that lookslike this:

    AA_ = Asyn%hronous a5aS%ript and _;CSS = Cas%adin- Style Sheets

    H1; = Hyper 1ext arRup ;an-ua-ePHP = PHP Hypertext Prepro%essorSU; = Stru%tured Uuery ;an-ua-e

    S7: = S%ala.le 7e%tor :raphi%s_; = _tensi.le arRup ;an-ua-e

    .he ,-, co&e to rea& the file an& #rite it to the output buffer is as follo#s $therea&file$% function returns the number of bytes rea& on success%:

    Example

  • 8/19/2019 Php w3 School

    75/129

    SU; = Stru%tured Uuery ;an-ua-eS7: = S%ala.le 7e%tor :raphi%s

    _; = _tensi.le arRup ;an-ua-e

    .he first parameter of fopen$% contains the name of the file to be opene& an& thesecon& parameter specifies in #hich mo&e the file shoul& be opene&( .he follo#ing

    example also generates a message if the fopen$% function is unable to open thespecifie& file:

    Example

  • 8/19/2019 Php w3 School

    76/129

    ,-, 0ea& )ile 2 frea&$%

    .he frea&$% function rea&s from an open file(

    .he first parameter of frea&$% contains the name of the file to rea& from an& the secon&parameter specifies the maximum number of bytes to rea&(

    .he follo#ing ,-, co&e rea&s the "#eb&ictionary(txt" file to the en&:

    /read2$0yLle9Llesi#e2'we.di%tionary+txt'33!

    ,-, 7lose )ile 2 fclose$%

    .he fclose$% function is use& to close an open file(

    tNs a goo& programming practice to close all files after you ha'e finishe& #ith them( oopen file running aroun& on your ser'er taking up resources

    .he fclose$% reuires the name of the file $or a 'ariable that hol&s the filename% #e#ant to close:

  • 8/19/2019 Php w3 School

    77/129

    Example

  • 8/19/2019 Php w3 School

    78/129

    .he example belo# rea&s the "#eb&ictionary(txt" file character by character* until en&2of2file is reache&:

    Example

  • 8/19/2019 Php w3 School

    79/129

    $0yLle = /open2'testLle+txt'9 'w'3

    ,-, )ile ,ermissions

    f you are ha'ing errors #hen trying to get this co&e to run* check that you ha'egrante& your ,-, file access to #rite information to the har& &ri'e(

    ,-, 9rite to )ile 2 f#rite$%

    .he f#rite$% function is use& to #rite to a file(

    .he first parameter of f#rite$% contains the name of the file to #rite to an& the secon&parameter is the string to be #ritten(

    .he example belo# #rites a couple of names into a ne# file calle& "ne#file(txt":

    Example

  • 8/19/2019 Php w3 School

    80/129

    ,-, ?'er#riting

    Do# that "ne#file(txt" contains some &ata #e can sho# #hat happens #hen #e open

    an existing file for #riting( All the existing &ata #ill be E0A

  • 8/19/2019 Php w3 School

    81/129

    .o allo# users to uploa& files from a form can be 'ery useful(

    Look at the follo#ing -.ML form for uploa&ing files:

  • 8/19/2019 Php w3 School

    82/129

    .he first parameter is the formNs input name an& the secon& in&ex can be either"name"* "type"* "sie"* "tmp/name" or "error"( Like this:

    • 1/)LE

  • 8/19/2019 Php w3 School

    83/129

  • 8/19/2019 Php w3 School

    84/129

    9hat is a 7ookieU

    A cookie is often use& to i&entify a user( A cookie is a small file that the ser'er embe&s

    on the userNs computer( Each time the same computer reuests a page #ith a bro#ser*it #ill sen& the cookie too( 9ith ,-,* you can both create an& retrie'e cookie 'alues(

    -o# to 7reate a 7ookieU

    .he setcookie$% function is use& to set a cookie(

    Note: .he setcookie$% function must appear @E)?0E the OhtmlP tag(

    "yntaxset%ooRie2na0e9 5alue9 expire9 path9 do0ain3!

    'xample 1n the example belo#* #e #ill create a cookie name& "user" an& assign the 'alue "Alex,orter" to it( 9e also specify that the cookie shoul& expire after one hour:

  • 8/19/2019 Php w3 School

    85/129

    n the example abo'e the expiration time is set to a month $60 sec * 60 min * 24hours * 30 days%(

    -o# to 0etrie'e a 7ookie ValueU.he ,-, 1/7??E 'ariable is use& to retrie'e a cookie 'alue(

    n the example belo#* #e retrie'e the 'alue of the cookie name& "user" an& &isplay iton a page:

  • 8/19/2019 Php w3 School

    86/129

    set%ooRie2'user'9 ''9 ti0e23"**3!?&

    9hat if a @ro#ser 8oes D?.

  • 8/19/2019 Php w3 School

    87/129

    ,-,

  • 8/19/2019 Php w3 School

    88/129

    $GSSSBN>5iews@=)!?&

  • 8/19/2019 Php w3 School

    89/129

    ou can also completely &estroy the session by calling the session/&estroy$% function:

  • 8/19/2019 Php w3 School

    90/129

    Assume #e ha'e the follo#ing ,-, co&e on a page:

  • 8/19/2019 Php w3 School

    91/129

    ,-, Mail 0eference

    )or more information about the ,-, mail$% function* 'isit our ,-, Mail 0eference(

    "ecure e%mails

    .here is a #eakness in the ,-, e2mail script in the pre'ious chapter(

    ,-,

  • 8/19/2019 Php w3 School

    92/129

      $0ail%he%R = spa0%he%R2$GPS1>'/ro0'@3!  i/ 2$0ail%he%R==FA;S3 4  e%ho 'Bn5alid input'!  8 else 4  $/ro0 = $GPS1>'/ro0'@! ,, sender  $su.Qe%t = $GPS1>'su.Qe%t'@!

      $0essa-e = $GPS1>'0essa-e'@!  ,, 0essa-e lines should not ex%eed J* %hara%ters 2PHP rule39 so wrap it  $0essa-e = wordwrap2$0essa-e9 J*3!  ,, send 0ail  0ail2'we.0asterexa0ple+%o0'9$su.Qe%t9$0essa-e9'Fro06 $/ro0[n'3!  e%ho '1hanR you /or sendin- us /eed.a%R'!  8  88?&

  • 8/19/2019 Php w3 School

    93/129

    • Error reporting

    @asic Error -an&ling: Fsing the &ie$% function

    .he first example sho#s a simple script that opens a text file:

  • 8/19/2019 Php w3 School

    94/129

    Don2fatal run2time errors( Execution of the script is not h

    G E/D?.7E 0un2time notices( .he script foun& something that mightcoul& also happen #hen running a script normally

    H56 E/F

  • 8/19/2019 Php w3 School

    95/129

      e%ho 'ndin- S%ript'!  die23!8

    .he co&e abo'e is a simple error han&ling function( 9hen it is triggere&* it gets theerror le'el an& an error message( t then outputs the error le'el an& message an&

    terminates the script(

    Do# that #e ha'e create& an error han&ling function #e nee& to &eci&e #hen it shoul&be triggere&(

  • 8/19/2019 Php w3 School

    96/129

    .rigger an Error

    n a script #here users can input &ata it is useful to trigger errors #hen an illegal inputoccurs( n ,-,* this is &one by the trigger/error$% function(

    Examplen this example an error occurs if the "test" 'ariable is bigger than "+":

  • 8/19/2019 Php w3 School

    97/129

    ,,set error handlersetGerrorGhandler2'%usto0rror'9GTSMGWAMNBN:3!

    ,,tri--er error$test=!

    i/ 2$test&)3 4  tri--erGerror2'7alue 0ust .e ) or .elow'9GTSMGWAMNBN:3!8?&

    .he output of the co&e abo'e shoul& be something like this:

    *rror& >)@ 7alue 0ust .e ) or .elowndin- S%ript

    Do# that #e ha'e learne& to create our o#n errors an& ho# to trigger them* lets take alook at error logging(

    Error Logging

    @y &efault* ,-, sen&s an error log to the ser'erNs logging system or a file* &epen&ingon ho# the error/log configuration is set in the php(ini file( @y using the error/log$%function you can sen& error logs to a specifie& file or a remote &estination(

  • 8/19/2019 Php w3 School

    98/129

      tri--erGerror2'7alue 0ust .e ) or .elow'9GTSMGWAMNBN:3!8?&

    .he output of the co&e abo'e shoul& be something like this:

    *rror& >)@ 7alue 0ust .e ) or .elowWe.0aster has .een notiLed

    An& the mail recei'e& from the co&e abo'e looks like this:

    rror6 >)@ 7alue 0ust .e ) or .elow

    .his shoul& not be use& #ith all errors( 0egular errors shoul& be logge& on the ser'erusing the &efault ,-, logging system(

    'xception handlin#

    Exceptions are use& to change the normal flo# of a script if a specifie& error occurs(

    9hat is an Exception

    9ith ,-, 5 came a ne# obect oriente& #ay of &ealing #ith errors(

    Exception han&ling is use& to change the normal flo# of the co&e execution if aspecifie& error $exceptional% con&ition occurs( .his con&ition is calle& an exception(

    .his is #hat normally happens #hen an exception is triggere&:

    • .he current co&e state is sa'e&

    • .he co&e execution #ill s#itch to a pre&efine& $custom% exception han&lerfunction

    • 8epen&ing on the situation* the han&ler may then resume the execution fromthe sa'e& co&e state* terminate the script execution or continue the script from a&ifferent location in the co&e

    9e #ill sho# &ifferent error han&ling metho&s:

    • @asic use of Exceptions

    • 7reating a custom exception han&ler

    • Multiple exceptions

  • 8/19/2019 Php w3 School

    99/129

    • 0e2thro#ing an exception

  • 8/19/2019 Php w3 School

    100/129

    H( .hro# 2 .his is ho# you trigger an exception( Each "thro#" must ha'e at leastone "catch"

    J( 7atch 2 A "catch" block retrie'es an exception an& creates an obect containingthe exception information

    Lets try to trigger an exception #ith 'ali& co&e:

  • 8/19/2019 Php w3 School

    101/129

    -o#e'er* one #ay to get aroun& the "e'ery thro# must ha'e a catch" rule is to set atop le'el exception han&ler to han&le errors that slip through(

    7reating a 7ustom Exception 7lass

    7reating a custom exception han&ler is uite simple( 9e simply create a special class#ith functions that can be calle& #hen an exception occurs in ,-,( .he class must be anextension of the exception class(

    .he custom exception class inherits the properties from ,-,Ns exception class an& youcan a&& custom functions to it(

    Lets create an exception class:

  • 8/19/2019 Php w3 School

    102/129

    +( .he customException$% class is create& as an extension of the ol& exceptionclass( .his #ay it inherits all metho&s an& properties from the ol& exception class

    H( .he errorMessage$% function is create&( .his function returns an error message if an e2mail a&&ress is in'ali&

    J( .he 1email 'ariable is set to a string that is not a 'ali& e2mail a&&ress

    X( .he "try" block is execute& an& an exception is thro#n since the e2mail a&&ressis in'ali&

    5( .he "catch" block catches the exception an& &isplays the error message

    Multiple Exceptions

    t is possible for a script to use multiple exceptions to check for multiple con&itions(

    t is possible to use se'eral if((else blocks* a s#itch* or nest multiple exceptions( .heseexceptions can use &ifferent exception classes an& return &ifferent error messages:

  • 8/19/2019 Php w3 School

    103/129

      e%ho $e&-etessa-e23!8?&

    Example explaine&:

    .he co&e abo'e tests t#o con&itions an& thro#s an exception if any of the con&itionsare not met:

    +( .he customException$% class is create& as an extension of the ol& exceptionclass( .his #ay it inherits all metho&s an& properties from the ol& exception class

    H( .he errorMessage$% function is create&( .his function returns an error message if an e2mail a&&ress is in'ali&

    J( .he 1email 'ariable is set to a string that is a 'ali& e2mail a&&ress* but containsthe string "example"

    X( .he "try" block is execute& an& an exception is not thro#n on the first con&ition

    5( .he secon& con&ition triggers an exception since the e2mail contains the string"example"

    6( .he "catch" block catches the exception an& &isplays the correct error message

    f the exception thro#n #ere of the class customException an& there #ere nocustomException catch* only the base exception catch* the exception #oul& be han&le&there(

    0e2thro#ing Exceptions

  • 8/19/2019 Php w3 School

    104/129

    $e0ail = 'so0eoneexa0ple+%o0'!

    try 4  try 4  ,,%he%R /or 'exa0ple' in 0ail address  i/2strpos2$e0ail9 'exa0ple'3 (== FA;S3 4

      ,,throw ex%eption i/ e0ail is not 5alid  throw new x%eption2$e0ail3!  8  8  %at%h2x%eption $e3 4  ,,rethrow ex%eption  throw new %usto0x%eption2$e0ail3!  88

    %at%h 2%usto0x%eption $e3 4  ,,display %usto0 0essa-e  e%ho $e&erroressa-e23!8?&

    Example explaine&:

    .he co&e abo'e tests if the email2a&&ress contains the string "example" in it* if it &oes*the exception is re2thro#n:

    +( .he customException$% class is create& as an extension of the ol& exceptionclass( .his #ay it inherits all metho&s an& properties from the ol& exception class

    H( .he errorMessage$% function is create&( .his function returns an error message if an e2mail a&&ress is in'ali&

    J( .he 1email 'ariable is set to a string that is a 'ali& e2mail a&&ress* but containsthe string "example"

    X( .he "try" block contains another "try" block to make it possible to re2thro# theexception

    5( .he exception is triggere& since the e2mail contains the string "example"

    6( .he "catch" block catches the exception an& re2thro#s a "customException"

    I( .he "customException" is caught an& &isplays an error message

    f the exception is not caught in its current "try" block* it #ill search for a catch block on"higher le'els"(

  • 8/19/2019 Php w3 School

    105/129

  • 8/19/2019 Php w3 School

    106/129

    .o test* 'ali&ate an& filter user input or custom &ata is an important part of any #ebapplication(

    .he ,-, filter extension is &esigne& to make &ata filtering easier an& uicker(

    9hy use a )ilterU

    Almost all #eb applications &epen& on external input( Fsually this comes from a user oranother application $like a #eb ser'ice%( @y using filters you can be sure yourapplication gets the correct input type(

    ou should always )ilter all external data!

    nput filtering is one of the most important application security issues(

    9hat is external &ataU

    • nput &ata from a form

    • 7ookies

    • 9eb ser'ices &ata

    • et one input 'ariable an& filter it

    • filter/input/array 2 >et se'eral input 'ariables an& filter them #ith the same or&ifferent filters

    n the example belo#* #e 'ali&ate an integer using the filter/'ar$% function:

  • 8/19/2019 Php w3 School

    107/129

    i/2(LlterG5ar2$int9 FB;1MG7A;BDA1GBN133 4  e%ho2'Bnte-er is not 5alid'3!8 else 4  e%ho2'Bnte-er is 5alid'3!8

    ?&

    .he co&e abo'e uses the ")L.E0/VAL8A.E/D." filter to filter the 'ariable(

  • 8/19/2019 Php w3 School

    108/129

  • 8/19/2019 Php w3 School

    109/129

    Example Explaine&

    .he example abo'e has an input $email% sent to it using the ">E." metho&:

    +( 7heck if an "email" input 'ariable of the ">E." type exists

    H( f the input 'ariable exists* check if it is a 'ali& e2mail a&&ress

  • 8/19/2019 Php w3 School

    110/129

    A form almost al#ays consist of more than one input fiel&( .o a'oi& calling the filter/'aror filter/input functions o'er an& o'er* #e can use the filter/'ar/array or thefilter/input/array functions(

    n this example #e use the filter/input/array$% function to filter three >E. 'ariables(.he recei'e& >E. 'ariables are a name* an age an& an e2mail a&&ress:

  • 8/19/2019 Php w3 School

    111/129

    .he secon& parameter of the filter/input/array$% function can be an array or a singlefilter 8(

    f the parameter is a single filter 8 all 'alues in the input array are filtere& by thespecifie& filter(

    f the parameter is an array it must follo# these rules:

    • Must be an associati'e array containing an input 'ariable as an array key $likethe "age" input 'ariable%

    • .he array 'alue must be a filter 8 or an array specifying the filter* flags an&options

    Fsing )ilter 7allback

    t is possible to call a user &efine& function an& use it as a filter using the)L.E0/7ALL@A7 filter( .his #ay* #e ha'e full control of the &ata filtering(

    ou can create your o#n user &efine& function or use an existing ,-, function

    .he function you #ish to use to filter is specifie& the same #ay as an option is specifie&(n an associati'e array #ith the name "options"

    n the example belo#* #e use a user create& function to con'ert all "/" to #hitespaces:

  • 8/19/2019 Php w3 School

    112/129

    H( 7all the filter/'ar$% function #ith the )L.E0/7ALL@A7 filter an& an arraycontaining our function

    H atabase

    ,y"G8 intro

    9ith ,-,* you can connect to an& manipulate &atabases(

    My

  • 8/19/2019 Php w3 School

    113/129

    ,-, ! Myoogle%(

    Look at http:###(mysl(comcustomers for an o'er'ie# of companies using My

  • 8/19/2019 Php w3 School

    114/129

    ?pen a 7onnection to the My

  • 8/19/2019 Php w3 School

    115/129

    .he connection #ill be close& automatically #hen the script en&s( .o close theconnection before* use the mysli/close$% function:

  • 8/19/2019 Php w3 School

    116/129

    7reate a .able

    .he 70EA.E .A@LE statement is use& to create a table in My

  • 8/19/2019 Php w3 School

    117/129

    .he follo#ing example sets the ,8 fiel& as the primary key fiel&( .he primary key fiel&is often an 8 number* an& is often use& #ith the AF.?/D70EMED. setting(AF.?/D70EMED. automatically increases the 'alue of the fiel& by + each time a ne#recor& is a&&e&( .o ensure that the primary key fiel& cannot be null* #e must a&& theD?. DFLL setting to the fiel&:

    $sXl = 'CMA1 1A; Persons2PBD BN1 N1 NT;; AT1GBNCMN19PMBAMY KY2PBD39

    FirstNa0e CHAM2)39;astNa0e CHAM2)39A-e BN1

    3'!

    ,y"G8 insert into

    .he D

  • 8/19/2019 Php w3 School

    118/129

    'xamplen the pre'ious chapter #e create& a table name& ",ersons"* #ith three columnsT")irstDame"* "LastDame" an& "Age"( 9e #ill use the same table in this example( .hefollo#ing example a&&s t#o ne# recor&s to the ",ersons" table:

  • 8/19/2019 Php w3 School

    119/129

    .he "insert(php" file connects to a &atabase* an& retrie'es the 'alues from the form#ith the ,-, 1/,?

  • 8/19/2019 Php w3 School

    120/129

    .o learn more about

  • 8/19/2019 Php w3 School

    121/129

  • 8/19/2019 Php w3 School

    122/129

    "yntaxS;C1 %olu0nGna0e2s3

    FM ta.leGna0eWHM %olu0nGna0e operator 5alue

    .o learn more about

  • 8/19/2019 Php w3 School

    123/129

    "yntaxS;C1 %olu0nGna0e2s3

    FM ta.leGna0eMDM Y %olu0nGna0e2s3 ASC\DSC

    .o learn more about

  • 8/19/2019 Php w3 School

    124/129

    /pdate

    .he F,8A.E statement is use& to mo&ify &ata in a table(

    Fp&ate 8ata n a 8atabase

    .he F,8A.E statement is use& to up&ate existing recor&s in a table(

    "yntaxTPDA1 ta.leGna0eS1 %olu0n)=5alue9 %olu0n=5alue9+++WHM so0eG%olu0n=so0eG5alue

    Note: Dotice the 9-E0E clause in the F,8A.E syntax( .he 9-E0E clause specifies#hich recor& or recor&s shoul& be up&ate&( f you omit the 9-E0E clause* all recor&s#ill be up&ate&

    .o learn more about

  • 8/19/2019 Php w3 School

    125/129

    0ysXliG%lose2$%on3!?&

    After the up&ate* the ",ersons" table #ill look like this:

    2irstName 8astName

    ,eter >riffin

    >lenn uagmire

    elete

    .he 8ELE.E statement is use& to &elete recor&s in a table(

    8elete 8ata n a 8atabase

    .he 8ELE.E )0?M statement is use& to &elete recor&s from a &atabase table(

    "yntaxD;1 FM ta.leGna0e

    WHM so0eG%olu0n = so0eG5alue

    Note: Dotice the 9-E0E clause in the 8ELE.E syntax( .he 9-E0E clause specifies#hich recor& or recor&s that shoul& be &elete&( f you omit the 9-E0E clause* all

    recor&s #ill be &elete&

    .o learn more about

  • 8/19/2019 Php w3 School

    126/129

  • 8/19/2019 Php w3 School

    127/129

    Dote that this configuration has to be &one on the computer #here your #eb site islocate&( f you are running nternet nformation

  • 8/19/2019 Php w3 School

    128/129

    .he co&e line belo# returns the 'alue of the first fiel& from the recor&:

    $%o0pna0e=od.%Gresult2$rs9)3!

    .he co&e line belo# returns the 'alue of a fiel& calle& "7ompanyDame":

    $%o0pna0e=od.%Gresult2$rs9'Co0panyNa0e'3!

    7losing an ?8@7 7onnection

    .he o&bc/close$% function is use& to close an ?8@7 connection(

    od.%G%lose2$%onn3!

    An ?8@7 Example

    .he follo#ing example sho#s ho# to first create a &atabase connection* then a result2set* an& then &isplay the &ata in an -.ML table(

  • 8/19/2019 Php w3 School

    129/129

      e%ho '