SlideShare une entreprise Scribd logo
1  sur  107
1


                                                PHP Notes
     Outline
     26.1           Introduction
     26.2           PHP
     26.3           String Processing and Regular Expressions
     26.4           Viewing Client/Server Environment Variables
     26.5           Form Processing and Business Logic
     26.6           Verifying a Username and Password
     26.7           Connecting to a Database
     26.8           Cookies
     26.9           Dynamic Content in PHP
     26.10          Operator Precedence
     26.11          Web Resources




2003 Prentice Hall, Inc. All rights reserved.
2

                                                Objectives

    In this chapter, you will learn:
           – To understand PHP data types, operators, arrays and control
             structures.
           – To understand string processing and regular expressions in
             PHP.
           – To construct programs that process form data.
           – To be able to read and write client data using cookies.
           – To construct programs that interact with MySQL databases.




2003 Prentice Hall, Inc. All rights reserved.
3

                                           26.1 Introduction

    • PHP
           –    PHP: Hypertext Preprocessor
           –    Originally called “Personal Home Page Tools”
           –    Popular server-side scripting technology
           –    Open-source
                   • Anyone may view, modify and redistribute source code
                   • Supported freely by community
           – Platform independent




2003 Prentice Hall, Inc. All rights reserved.
4

                                                26.2 PHP

    • Basic application
           – Scripting delimiters
                   • <? php ?>
                   • Must enclose all script code
           – Variables preceded by $ symbol
                   • Case-sensitive
           – End statements with semicolon
           – Comments
                   • // for single line
                   • /* */ for multiline
           – Filenames end with .php by convention



2003 Prentice Hall, Inc. All rights reserved.
1    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
                                                                                                                          5
2         "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
                                                                                                     Outline
3
4    <!-- Fig. 26.1: first.php -->
5    <!-- Our first PHP script -->                                                          first.php
6                                               Scripting delimiters                        (1 of 1)
7    <?php
8         $name = "LunaTic";   // declaration
9    ?>                                                           Declare variable $name
10
11 <html xmlns = "http://www.w3.org/1999/xhtml">
12        <head>
13           <title>A simple PHP document</title>Single-line   comment
14        </head>
15
16        <body style = "font-size: 2em">
17           <p>
18              <strong>
19
20                  <!-- print variable name’s value -->
21                  Welcome to PHP, <?php print( "$name" ); ?>!
22              </strong>
23           </p>
24        </body>
                                                               Function print outputs the value of variable
                                                               $name
25 </html>




                                                                                               2003 Prentice Hall, Inc.
                                                                                            All rights reserved.
6

                                                26.2 PHP
 Fig. 26.1    Simple PHP program.




2003 Prentice Hall, Inc. All rights reserved.
7

                                                26.2 PHP

    • Variables
           – Can have different types at different times
           – Variable names inside strings replaced by their value
           – Type conversions
                   • settype function
                   • Type casting
           – Concatenation operator
              • . (period)
                   • Combine strings




2003 Prentice Hall, Inc. All rights reserved.
8

                                                26.2 PHP

         Data type      Description
        int, integer Whole numbers (i.e., numbers without a decimal point).
        float, double Real numbers (i.e., numbers containing a decimal point).
        string          Text enclosed in either single ('') or double ("") quotes.
        bool, Boolean True or false.
        array           Group of elements of the same type.
        object          Group of associated data and methods.
        Resource        An external data source.
        NULL            No value.
        Fig. 26.2 PHP data types.




2003 Prentice Hall, Inc. All rights reserved.
1    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
                                                                                                                         9
2       "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">                                  Outline
3
4    <!-- Fig. 26.3: data.php               -->
5    <!-- Demonstration of PHP data types -->                                              data.php
6                                                                                          (1 of 3)
7    <html xmlns = "http://www.w3.org/1999/xhtml">
8       <head>
9          <title>PHP data types</title>
10      </head>
11
12      <body>
13
14         <?php                           Assign a string to variable
15
                                           $testString
16               // declare a string, double and integer
17               $testString = "3.5 seconds";
18               $testDouble = 79.2;
                                                           Assign a double to variable
                                                           $testDouble
                                                           Assign an integer to variable
19               $testInteger = 12;
                                                           $testInteger
20         ?>
21




                                                                                              2003 Prentice Hall, Inc.
                                                                                           All rights reserved.
22   <!-- print each variable’s value -->
                                                                                                               10
     <?php print( $testString ); ?> is a string.<br />
23
                                                                                          Outline
24   <?php print( $testDouble ); ?> is a double.<br />
25   <?php print( $testInteger ); ?> is an integer.<br />
26                                                                                 data.php
27   <br />                                                  Print each variable’s (2 of 3)
                                                                                   value
28   Now, converting to other types:<br />
29   <?php
30
31      // call function settype to convert variable
32      // testString to different data types
33      print( "$testString" );
34      settype( $testString, "double" );
35      print( " as a double is $testString <br />" );
36      print( "$testString" );
37      settype( $testString, "integer" );
38      print( " as an integer is $testString <br />" );
39      settype( $testString, "string" );
40                               Call function settype
        print( "Converting back to a string results in to
41         $testString <br /><brfunction settypetype of
                           Call />" ); the data to
                                 convert
42                               variable $testString to a
                           convert the data type of
43      $data = "98.6 degrees"; double.
                           variable $testString to an
                           integer.
                            Convert variable $testString
                            back to a string


                                                                                    2003 Prentice Hall, Inc.
                                                                                 All rights reserved.
44
                                                                                                                      11
              // use type casting to cast variables to a
45
                                                                                                 Outline
46            // different type
47            print ( "Now using type casting instead: <br />
48               As a string - " . ( string ) $data .                                   data.php
49               "<br />As a double     - " . (double ) $data .                         (3 of 3)
50               "<br />As an integer     - " . ( integer ) $data );
51       ?>
                                                                       Use type casting to cast variable
52    </body>
                                                                       $data to different types
53 </html>




                                                                                           2003 Prentice Hall, Inc.
                                                                                        All rights reserved.
12

                                                26.2 PHP
 Fig. 26.3    Type conversion.




2003 Prentice Hall, Inc. All rights reserved.
13

                                                26.2 PHP

    • Arithmetic operators
           – Assignment operators
                   • Syntactical shortcuts
                   • Before being assigned values, variables have value undef
    • Constants
           – Named values
           – define function




2003 Prentice Hall, Inc. All rights reserved.
1    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
                                                                                                                  14
2       "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">                           Outline
3
4    <!-- Fig. 26.4: operators.php       -->
5    <!-- Demonstration of operators -->                                            operators.php
6                                                                                   (1 of 3)
7    <html xmlns = "http://www.w3.org/1999/xhtml">
8       <head>
9          <title>Using arithmetic operators</title>
10      </head>
11
12      <body>
13         <?php
14               $a = 5;       Define constant VALUE.
15               print( "The value of variable a is $a <br />" );
16
17               // define constant VALUE
                                               Add constant VALUE to variable $a.
18               define( "VALUE", 5 );
19
20               // add constant VALUE to variable $a
21               $a = $a + VALUE;
22               print( "Variable a after adding constant VALUE
23                 is $a <br />" );
24




                                                                                       2003 Prentice Hall, Inc.
                                                                                    All rights reserved.
25   // multiply variable $a by 2
                                                                                                             15
     $a *= 2;
26
                                    Multiply variable $a by two using the               Outline
27   print( "Multiplying variable a by 2 yields $a <br />" );
                                    multiplication assignment operator *=.
28
29   // test if variable $a is less than 50                                       operators.php
                                                   Test than 50 variable $a is less than 50
                             Print if variable $a is lesswhether .
30   if ( $a < 50 )                                                               (2 of 3)
31      print( "Variable a is less than 50 <br />" );
32
33   // add 40 to variable $a
                                  Add 40 to variable $a using the addition assignment
34   $a += 40;
                                  operator +=.
35   print( "Variable a after adding 40 is $a <br />" );
36
37   // test if variable $a is 50 or less
38   if ( $a < 51 )
39      print( "Variable a is still 50 or less<br />" );
40
41   // test if variable $a is between 50 and 100, inclusive
42   elseif ( $a < 101 )
43      print( "Variable a is now between 50 and 100,
44          inclusive<br />" );
45   else
46      print( "Variable a is now greater than 100
47          <br />" );
48




                                                                                  2003 Prentice Hall, Inc.
                                                                               All rights reserved.
49           // print an uninitialized variable
                                                                                                                 16
50           print( "Using a variable before initializing:
                                                                                            Outline
51              $nothing <br />" );
52
53           // add constant VALUE to an uninitialized variable                    operators.php
54           $test = $num + VALUE;                                                 (3 of 3)
55           print( "An uninitialized variable plus constant
56              VALUE yields $test <br />" );
57                                 Print an uninitializedVALUE to ($nothing).
                                          Add constant variable an uninitialized
58           // add a string to an integer
                                         variable.
59           $str = "3 dollars";
60           $a += $str;
61           print( "Adding a string to variable a yields $a
62              <br />" );
63      ?>
64    </body>
                                      Add a string to an integer.
65 </html>




                                                                                      2003 Prentice Hall, Inc.
                                                                                   All rights reserved.
17

                                                  26.2 PHP
 Fig. 26.4    Using PHP’s arithmetic operators.




2003 Prentice Hall, Inc. All rights reserved.
18

                                                26.2 PHP

    • Keywords
           – Reserved for language features
           – if…elseif…else
    • Arrays
           – Group of related data
                   • Elements
           – Name plus braces and index
                   • Indices start at zero
           – count function
           – array function




2003 Prentice Hall, Inc. All rights reserved.
19

                                                26.2 PHP

    • Arrays, cont.
           – Built-in iterators
                   • Maintain pointer to element currently referenced
                   • reset
                   • key
                   • next
                   • foreach loops




2003 Prentice Hall, Inc. All rights reserved.
20

                                                26.2 PHP


       PHP keywords
       and                            do        for        include   require   true
       break                          else      foreach    list      return    var
       case                           elseif    function   new       static    virtual
       class                          extends   global     not       switch    xor
       continue                       false     if         or        this      while
       default
       Fig. 26.5 PHP keywords.




2003 Prentice Hall, Inc. All rights reserved.
1    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
                                                                                                                        21
2       "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">                                 Outline
3
4    <!-- Fig. 26.6: arrays.php -->
5    <!-- Array manipulation      -->                                                     arrays.php
6                                                                                         (1 of 3)
7    <html xmlns = "http://www.w3.org/1999/xhtml">
8       <head>
9          <title>Array manipulation</title>
10      </head>
11
12      <body>
13         <?php                         Create the array $first by assigning a value
14                                       to an array element.
15               // create array first
16               print( "<strong>Creating the first array</strong>
17                  <br />" );
18               $first[ 0 ] = "zero";
19               $first[ 1 ] = Assign
                               "one"; a value to the array, omitting the index.
20               $first[ 2 ] = Appends a Use a for loop to print outthe array.
                               "two";     new element to the end of each element’s index and value.
21               $first[] = "three";     Function count returns the total number of elements in the
22                                       array.
23               // print each element’s index and value
24               for ( $i = 0; $i < count( $first ); $i++ )
25                  print( "Element $i is $first[$i] <br />" );



                                                                                             2003 Prentice Hall, Inc.
                                                                                          All rights reserved.
26
                                                                                                                  22
     print( "<br /><strong>Creating the second array
27
                                                                                           Outline
                                             Call function array to create an array that contains
28      </strong><br />" );
29                                           the arguments passed to it. Store the array in variable
30   // call function                        $second
                        array to create array second .                              arrays.php
31   $second = array(   "zero", "one", "two", "three" );                            (2 of 3)
32   for ( $i = 0; $i < count( $second ); $i++ )
33      print( "Element $i is $second[$i] <br />" );
34
35   print( "<br /><strong>Creating the third array
36      </strong><br />" );
37
38   // assign values to non-numerical indices
39   $third[ "ArtTic" ] = 21;
                              Assign values to non-numerical indices
40   $third[ "LunaTic" ] = 18;
                              in array $third.
41   $third[ "GalAnt" ] =   23;
                                  Function reset sets the internal pointer to the
42
                                  first element of the array.
43   // iterate through the array elements and print each
44   // element’s name and value
45   for ( reset( $third ); $element = key( $third );
46      next( $third ) )
47      print( "$element is $third[$element] <br />" );
48                        Function key returns the index of the element which
                          the internal pointer references.
                        Function next moves the internal pointer to the next
                        element.
                                                                                       2003 Prentice Hall, Inc.
                                                                                    All rights reserved.
49           print( "<br /><strong>Creating the fourth array
                                                                                                                           23
                </strong><br />" );
50
                                                                                                        Outline
51
52           // call function array to create array fourth using
53           // string indices                                                               arrays.php
54           $fourth = array(                                                                (3 of 3)
55              "January"    => "first",     "February" => "second",
56              "March"      => "third",     "April"     => "fourth",
57              "May"        =>   "fifth",
                                            Operator =>=> used in function array to assign each
                                              "June"
                                                          is "sixth",
58              "July"       =>   "seventh", "August" string index. The value to the left of the
                                            element a => "eighth",
59              "September" =>    "ninth", operator is the array index, and the value to the right is
                                              "October" => "tenth",
60              "November"   =>             the element’s value.
                                  "eleventh","December" => "twelfth"
61              );
62
63           // print each element’s name and value
64           foreach ( $fourth as $element => $value )
65              print( "$element is the $value month <br />" );
66      ?>
67    </body>
68 </html>




                                                                                                2003 Prentice Hall, Inc.
                                                                                             All rights reserved.
24

                                                26.2 PHP
 Fig. 26.6    Array manipulation.




2003 Prentice Hall, Inc. All rights reserved.
25
                 26.3 String Processing and Regular
                             Expressions
    • String processing
           – Equality and comparison two important operations
           – strcmp function
                   • Returns –1 if string 1 < string 2
                   • Returns 0 if string 1 = string 2
                   • Returns 1 if string 1 > string 2
           – Relational operators




2003 Prentice Hall, Inc. All rights reserved.
1    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
                                                                                                                             26
2       "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">                                       Outline
3
4    <!-- Fig. 26.7: compare.php -->
5    <!-- String Comparison           -->                                                      compare.php
6                                                                                              (1 of 2)
7    <html xmlns = "http://www.w3.org/1999/xhtml">
8       <head>
9          <title>String Comparison</title>
10      </head>
11
12      <body>
13         <?php
                                      Use a for loop to iterate through each array element.
14
15               // create array fruits
16               $fruits = array( "apple", "orange", "banana" );
                                           Function strcmp compares two strings. If the first string
17
                                           alphabetically precedes the second, then –1 is returned. If
18               // iterate through   each array element
                                           the strings are equal, 0 is returned. If the first string
19               for ( $i = 0; $i <   count( $fruits ); $i++ ) {
                                           alphabetically follows the second, then 1 is returned.
20
21                  // call function strcmp to compare the array element
22                  // to string "banana"
23                 if ( strcmp( $fruits[ $i ], "banana" ) < 0 )
24                    print( $fruits[ $i ]." is less than banana " );




                                                                                                  2003 Prentice Hall, Inc.
                                                                                               All rights reserved.
25               elseif ( strcmp( $fruits[ $i ], "banana" ) > 0 )
                                                                                                                   27
                    print( $fruits[ $i ].
26
                                                                                              Outline
27                      " is greater than banana " );
28               else
29                  print( $fruits[ $i ]." is Use relational operators
                                              equal to banana " );   to compare each array
                                                                                       compare.php
30
                                              element to string “apple”.               (2 of 2)
31               // use relational operators to compare each element
32               // to string "apple"
33               if ( $fruits[ $i ] < "apple" )
34                 print( "and less than apple! <br />" );
35               elseif ( $fruits[ $i ] > "apple" )
36                 print( "and greater than apple! <br />" );
37               elseif ( $fruits[ $i ] == "apple" )
38                  print( "and equal to apple! <br />" );
39
40           }
41      ?>
42    </body>
43 </html>




                                                                                        2003 Prentice Hall, Inc.
                                                                                     All rights reserved.
28
                 26.3 String Processing and Regular
                             Expressions
 Fig. 26.7    Using the string comparison operators.




2003 Prentice Hall, Inc. All rights reserved.
29
                 26.3 String Processing and Regular
                             Expressions
    • Regular expressions
           – Pattern matching templates
           – ereg function
                   • POSIX
           – preg_match function
              • Perl
           – ereg_replace function
    • Building regular expressions
           – Metacharacters
                   • $, ., ^
           – Brackets [ ]



2003 Prentice Hall, Inc. All rights reserved.
1    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
                                                                                                                 30
2       "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">                          Outline
3
4    <!-- Fig. 26.8: expression.php -->
5    <!-- Using regular expressions -->                                            expression.php
6                                                                                  (1 of 3)
7    <html xmlns = "http://www.w3.org/1999/xhtml">
8       <head>
9          <title>Regular expressions</title>
10      </head>
11
12      <body>
13         <?php
                                         Function ereg searches for the literal
14               $search = "Now is   the characters Now inside variable $search.
                                          time";
15               print( "Test string is: '$search'<br /><br />" );
16
17               // call function ereg to search for pattern 'Now'
18               // in variable search
19               if ( ereg( "Now", $search ) )
20                  print( "String 'Now' was found.<br />" );
21




                                                                                      2003 Prentice Hall, Inc.
                                                                                   All rights reserved.
22   // search for pattern 'Now' in the beginning of
                                                                                                                    31
     // the string
23
                                                                                               Outline
24   if ( ereg( "^Now", $search ) )
                                         The dollar sign special character ($) search for the
25        print( "String 'Now' found at beginning
                                         pattern Now (^) matches the
                          The caret special character at the end of the string.
26           of the line.<br />" );                                                expression.php
27                        beginning of a string. Function ereg searches the        (2 of 3)
28   //                   beginning ofthe end of for pattern Now .
          search for pattern 'Now' at  the string the string
29   if ( ereg( "Now$", $search ) )
30        print( "String 'Now' was found at the end
31           of the line.<br />" );
32
33   // search for any word ending in 'ow'
34   if ( ereg( "[[:<:]]([a-zA-Z]*ow)[[:>:]]", $search,
35        $match ) )
36        print( "Word found ending in 'ow': " .
37           $match[ 1 ] . "<br />" );
38
                                          The special bracket parentheses, [a-zA-Z]*ow
                                    The expression inside the expressions [[:<:]] and ,
39   // search for any words beginning with 't'
                                      Placing a word in the in ow. The quantifier *
                                    matches anypatternending beginning and end of a
                                          [[:>:]] match parentheses stores the matched
40   print( "Words beginning      with 't' found: ");
41
                                          word, preceding pattern 0 or more times.
                                    matches in the array that is specified in the third argument
                                      string therespectively.
                                      to function ereg.
42   while ( eregi( "[[:<:]](t[[:alpha:]]+)[[:>:]]",
43        $search, $match ) ) {
44        print( $match[ 1 ] . " " );
                                               The pattern used in this example,
45
                                           [[:<:]](t[[:alpha:]]+)[[:>:]], matches any
                                The while word is used to find each occurrence of a
                                           loop beginning with the
                             Function eregi is used to specify case character t followed by one or
                                                                     insensitive
                                            string beginning with t.
                                word in themore characters. Character class [[:alpha:]]
                             pattern matches.
                                               recognizes any alphabetic character.      2003 Prentice Hall, Inc.
                                                                                      All rights reserved.
46                // remove the first occurrence of a word beginning
                                                                                                                        32
                  // with 't' to find other instances in the string
47
                                                                                                   Outline
48                $search = ereg_replace( $match[ 1 ], "", $search );
49            }
50                                                                                           expression.php
                                       After printing a match of a word beginning with t, function
51            print( "<br />" );       ereg_replace is called to remove the word from the of 3)
                                                                                             (3 string.
52       ?>                            This is necessary be because to find multiple instances of a
53    </body>
                                       given pattern, the first matched instance must first be removed.
54 </html>
                                       Function ereg_replace takes three arguments: the pattern to
                                       match, a string to replace the matched string and the string to
                                       search.




                                                                                             2003 Prentice Hall, Inc.
                                                                                          All rights reserved.
33
                 26.3 String Processing and Regular
                             Expressions
 Fig. 26.8    Regular expressions in PHP.




2003 Prentice Hall, Inc. All rights reserved.
34
                 26.3 String Processing and Regular
                             Expressions

       Quantifier                        Matches
       {n}                               Exactly n times.
       {m,n}                             Between m and n times inclusive.
       {n,}                              n or more times.
       +                                 One or more times (same as {1,}).
       *                                 Zero or more times (same as {0,}).
       ?                                 Zero or one time (same as {0,1}).
      Fig. 26.9                Some PHP quantifiers.




2003 Prentice Hall, Inc. All rights reserved.
35
                 26.3 String Processing and Regular
                             Expressions

    Character class                 Description
    alnum                           Alphanumeric characters (i.e., letters [a-zA-Z] or digits [0-9]).
    alpha                           Word characters (i.e., letters [a-zA-Z]).
    digit                           Digits.
    space                           Whitespace.
    lower                           Lowercase letters.
    upper                           Uppercase letters.
    Fig. 26.10             Some PHP character classes.




2003 Prentice Hall, Inc. All rights reserved.
36
           26.4 Viewing Client/Server Environment
                          Variables
    • Environment variables
           – Provide information about execution environment
                   • Type of Web browser
                   • Type of server
                   • Details of HTTP connection
           – Stored as array in PHP
                   • $_ENV




2003 Prentice Hall, Inc. All rights reserved.
37
           26.4 Viewing Client/Server Environment
                          Variables
               Variable name    Description
               $_SERVER         Data about the currently running server.
               $_ENV            Data about the client’s environment.
               $_GET            Data posted to the server by the get method.
               $_POST           Data posted to the server by the post method.
               $_COOKIE         Data contained in cookies on the client’s computer.
               $GLOBALS         Array containing all global variables.
               Fig. 26.11    Some useful global arrays.




2003 Prentice Hall, Inc. All rights reserved.
1    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
                                                                                                                     38
2       "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
                                                                                                Outline
3
4    <!-- Fig. 26.11: env.php                          -->
5    <!-- Program to display environment variables -->                                 env.php
6                                                                                      (1 of 1)
7    <html xmlns = "http://www.w3.org/1999/xhtml">
8       <head>
9          <title>Environment Variables</title>
10      </head>
11
12      <body>
13         <table border = "0" cellpadding = "2" cellspacing = "0"
14               width = "100%">
15         <?php
16
17               // print the key and value for each element
18               // in the $_ENV array
19               foreach ( $_ENV as $key => $value )
20                 print( "<tr><td bgcolor = "#11bbff">
21                               The foreach loop
                      <strong>$key</strong></td>   is used to print out the keys and
22                    <td>$value</td></tr>"each element in the $_ENV array.
                                 values for );
23         ?>                   PHP stores environment variables and their values in
24         </table>             the $_ENV array.
25      </body>
26 </html>


                                                                                          2003 Prentice Hall, Inc.
                                                                                       All rights reserved.
39
           26.4 Viewing Client/Server Environment
                          Variables
 Fig. 26.12    Displaying environment variables.




2003 Prentice Hall, Inc. All rights reserved.
40

       26.5 Form Processing and Business Logic

    • Form processing
           – action property
              • Where to send form data
           – method property
                   • post
           – Each element has unique name




2003 Prentice Hall, Inc. All rights reserved.
1    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
                                                                                                                             41
2       "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">                                      Outline
3
4    <!-- Fig. 26.13: form.html                      -->
5    <!-- Form for use with the form.php program -->                                           form.html
6                                                                                              (1 of 4)
7    <html xmlns = "http://www.w3.org/1999/xhtml">
8       <head>
9          <title>Sample form to take user input in XHTML</title>
10      </head>
11
12      <body>
13                                         The action attribute of the form element
14         <h1>This is                     indicates that when the user clicks Register, the
                           a sample registration form.</h1>
15         Please fill     in all fields and click Register. posted to form.php.
                                           form data will be
16
17         <!-- post form data to form.php -->
18         <form method = "post" action = "form.php">
19               <img src = "images/user.gif" alt = "User" /><br />
20               <span style = "color: blue">
21                 Please fill out the fields below.<br />
22               </span>
23




                                                                                                  2003 Prentice Hall, Inc.
                                                                                               All rights reserved.
24   <!-- create four text boxes for user input -->
                                                                                                          42
     <img src = "images/fname.gif" alt = "First Name" />
25
                                   A unique name (e.g., email) is assigned to each    Outline
     <input type = "text" name = "fname" /><br />
26
                                   of the form’s input fields. When Register is
27
                                   clicked, each field’s name and value are sent to
28   <img src = "images/lname.gif" alt = "Last Name" />
                                   the Web server.                             form.html
29   <input type = "text" name = "lname" /><br />                              (2 of 4)
30
31   <img src = "images/email.gif" alt = "Email" />
32   <input type = "text" name = "email" /><br />
33
34   <img src = "images/phone.gif" alt = "Phone" />
35   <input type = "text" name = "phone" /><br />
36
37   <span style = "font-size: 10pt">
38      Must be in the form (555)555-5555</span>
39   <br /><br />
40
41   <img src = "images/downloads.gif"
42      alt = "Publications" /><br />
43
44   <span style = "color: blue">
45      Which book would you like information about?
46   </span><br />
47




                                                                               2003 Prentice Hall, Inc.
                                                                            All rights reserved.
48   <!-- create drop-down list containing book names -->
                                                                                            43
     <select name = "book">
49
                                                                       Outline
50     <option>Internet and WWW How to Program 3e</option>
51     <option>C++ How to Program 4e</option>
52      <option>Java How to Program 5e</option>               form.html
53      <option>XML How to Program 1e</option>                (3 of 4)
54   </select>
55   <br /><br />
56
57   <img src = "images/os.gif" alt = "Operating System" />
58   <br /><span style = "color: blue">
59      Which operating system are you currently using?
60   <br /></span>
61
62   <!-- create five radio buttons -->
63   <input type = "radio" name = "os" value = "Windows XP"
64     checked = "checked" />
65      Windows XP
66
67   <input type = "radio" name = "os" value =
68      "Windows 2000" />
69     Windows 2000
70
71   <input type = "radio" name = "os" value =
72      "Windows 98" />
73     Windows 98<br />


                                                                 2003 Prentice Hall, Inc.
                                                              All rights reserved.
74
                                                                                                  44
             <input type = "radio" name = "os" value = "Linux" />
75
                                                                             Outline
76              Linux
77
78           <input type = "radio" name = "os" value = "Other" />   form.html
79              Other<br />                                         (4 of 4)
80
81            <!-- create a submit button -->
82           <input type = "submit" value = "Register" />
83       </form>
84
85    </body>
86 </html>




                                                                       2003 Prentice Hall, Inc.
                                                                    All rights reserved.
45

       26.5 Form Processing and Business Logic
 Fig. 26.13    XHTML form for gathering user input.




2003 Prentice Hall, Inc. All rights reserved.
46

       26.5 Form Processing and Business Logic

    • Business logic
           – Confirm that valid information was entered
           – extract function
                   • Creates variables corresponding to each key-value pair in array
                   • Easily retrieve all values sent to PHP page
           – Regular expressions very helpful
           – Do checks on client side where possible
                   • JavaScript
                   • Conserves server resources
    • Ending a script
           – die function
              • Remember to close all HTML tags


2003 Prentice Hall, Inc. All rights reserved.
1    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
                                                                                                                           47
2       "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">                                    Outline
3
4    <!-- Fig. 26.14: form.php                     -->
5    <!-- Read information sent from form.html -->                                           form.php
6                                                                                            (1 of 4)
7    <html xmlns = "http://www.w3.org/1999/xhtml">
8       <head>
9          <title>Form Validation</title>
10      </head>
11
12      <body style = "font-family: arial,sans-serif">
                                                        Function ereg is called to determine whether the
13                                  The parentheses in the expression must be
14         <?php
                                                        phone number entered by the user is valid.
                                                 three digits ([0-9]{3}), a the opening
                                    followed by The expression ( matches closing
15               extract( $_POST   );
                                    parenthesis, parentheses ofliteral hyphen and
                                                 three digits, a a phone number.
16                                  four additional digits.
17               // determine whether phone number is valid and print
18               // an error message if not
19               if ( !ereg( "^([0-9]{3})[0-9]{3}-[0-9]{4}$",
20                  $phone ) ){
21
                                            We access the phone field’s value from
                                            form.html by using variable $phone.




                                                                                                2003 Prentice Hall, Inc.
                                                                                             All rights reserved.
22            print( "<p><span style = "color: red;
                                                                                                                  48
                 font-size: 2em">
23
                                                                                             Outline
24               INVALID PHONE NUMBER</span><br />
25               A valid phone number must be in the form
26               <strong>(555)555-5555</strong><br />                               form.php
27               <span style = "color: blue">                                     (2 of 4)
28               Click the Back button, enter a valid phone
                                         Function die terminates script execution
29               number and resubmit.<br /><br />
30              Thank You.</span></p></body></html>" );
31
32            die(); // terminate script execution
33        }
34   ?>
35
36   <p>Hi
37        <span style = "color: blue">
38            <strong>
39               <?php print( "$fname" ); ?>
40            </strong>
41        </span>.
42        Thank you for completing the survey.<br />
43




                                                                                       2003 Prentice Hall, Inc.
                                                                                    All rights reserved.
44     You have been added to the
                                                                                               49
        <span style = "color: blue">
45
                                                                          Outline
46          <strong>
47              <?php print( "$book " ); ?>
48          </strong>                                            form.php
49      </span>                                                  (3 of 4)
50      mailing list.
51   </p>
52   <strong>The following information has been saved
53      in our database:</strong><br />
54
55   <table border = "0" cellpadding = "0" cellspacing = "10">
56      <tr>
57          <td bgcolor = "#ffffaa">Name </td>
58          <td bgcolor = "#ffffbb">Email</td>
59          <td bgcolor = "#ffffcc">Phone</td>
60          <td bgcolor = "#ffffdd">OS</td>
61      </tr>
62
63      <tr>
64          <?php
65




                                                                    2003 Prentice Hall, Inc.
                                                                 All rights reserved.
66                   // print each form field’s value
                                                                                             50
                     print( "<td>$fname $lname</td>
67
                                                                        Outline
68                      <td>$email</td>
69                      <td>$phone</td>
70                      <td>$os</td>" );                       form.php
71              ?>                                             (4 of 4)
72           </tr>
73       </table>
74
75       <br /><br /><br />
76       <div style = "font-size: 10pt; text-align: center">
77           This is only a sample form.
78           You have not been added to a mailing list.
79       </div>
80    </body>
81 </html>




                                                                  2003 Prentice Hall, Inc.
                                                               All rights reserved.
51

       26.5 Form Processing and Business Logic
 Fig. 26.14    Obtaining user input through forms.




2003 Prentice Hall, Inc. All rights reserved.
52

         26.6 Verifying a Username and Password

    • Private website
           – Only accessible to certain individuals
           – Encrypt username and password data when sending, storing
             and retrieving for increased security
    • Implementing password checking
           – Login information stored in file
                   • fopen function
                   • Read, write, append modes
           – Store data using fputs
                   • n newline character
           – Close files when done
                   • fclose function


2003 Prentice Hall, Inc. All rights reserved.
53

         26.6 Verifying a Username and Password

    • Implementing password checking, cont.
           – Trim newline character
                   • chop function
           – Split string into substrings given a certain delimiter
                   • split function
           – If username/password match list, allow access




2003 Prentice Hall, Inc. All rights reserved.
1    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
                                                                                                    54
2       "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
                                                                               Outline
3
4    <!-- Fig. 26.15: password.html                          -->
5    <!-- XHTML form sent to password.php for verification -->        password.html
6                                                                     (1 of 4)
7    <html xmlns = "http://www.w3.org/1999/xhtml">
8       <head>
9          <title>Verifying a username and a password.</title>
10
11         <style type = "text/css">
12               td { background-color: #DDDDDD }
13         </style>
14      </head>
15
16      <body style = "font-family: arial">
17         <p style = "font-size: 13pt">
18               Type in your username and password below.
19               <br />
20               <span style = "color: #0000FF; font-size: 10pt;
21                  font-weight: bold">
22                 Note that password will be sent as plain text
23               </span>
24         </p>
25




                                                                         2003 Prentice Hall, Inc.
                                                                      All rights reserved.
26   <!-- post form data to password.php -->
                                                                                                        55
     <form action = "password.php" method = "post">
27
                                                                                   Outline
28      <br />
29
                                   Form data is posted to password.php.
30      <table border = "0" cellspacing = "0"                             password.html
31         style = "height: 90px; width: 123px;                           (2 of 4)
32         font-size: 10pt" cellpadding = "0">
33
34         <tr>
35            <td colspan = "3">
36                 <strong>Username:</strong>
37            </td>
38         </tr>
39
40         <tr>
41            <td colspan = "3">
42                 <input size = "40" name = "USERNAME"
43                    style = "height: 22px; width: 115px" />
44            </td>
45         </tr>
46




                                                                             2003 Prentice Hall, Inc.
                                                                          All rights reserved.
47   <tr>
                                                                                       56
        <td colspan = "3">
48
                                                                  Outline
49           <strong>Password:</strong>
50      </td>
51   </tr>                                               password.html
52                                                       (3 of 4)
53   <tr>
54      <td colspan = "3">
55           <input size = "40" name = "PASSWORD"
56              style = "height: 22px; width: 115px"
57              type = "password" />
58      <br/></td>
59   </tr>
60
61   <tr>
62      <td colspan = "1">
63           <input type = "submit" name = "Enter"
64              value = "Enter" style = "height: 23px;
65              width: 47px" />
66      </td>
67     <td colspan = "2">
68           <input type = "submit" name = "NewUser"
69              value = "New User"
70              style = "height: 23px" />
71      </td>



                                                            2003 Prentice Hall, Inc.
                                                         All rights reserved.
72              </tr>
                                                      57
             </table>
73
                                 Outline
74       </form>
75    </body>
76 </html>              password.html
                        (4 of 4)




                           2003 Prentice Hall, Inc.
                        All rights reserved.
58

         26.6 Verifying a Username and Password
 Fig. 26.15    XHTML form for obtaining a username and password.




2003 Prentice Hall, Inc. All rights reserved.
1    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
                                                                                                                            59
2       "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">                                     Outline
3
4    <!-- Fig. 26.16: password.php                              -->
5    <!-- Searching a database for usernames and passwords. -->                               password.php
6                                                                                             (1 of 7)
7    <html xmlns = "http://www.w3.org/1999/xhtml">
8       <head>                          Variable names, when preceded by the logical
9          <?php                        negation operator (!), return true if they are empty
10               extract( $_POST );     or set to 0. This checks if a user has submitted a form
11                                      without specifying a username or password.
12               // check if user has left USERNAME or PASSWORD field blank
13               if ( !$USERNAME || !$PASSWORD ) {   Function fieldsBlank is called if the user has
14                   fieldsBlank();
                                                     Function isset tests whether the notify the user
                                                     submitted an incomplete form to user has
15                   die();
                                                     pressed form fields must be completed. that a
                                                     that all the New User button, indicating
16               }
                                                     new user must be added.
17
18               // check if the New User button was clicked new
                                                   To add a         user, we open the file
19               if ( isset( $NewUser ) ) {          password.txt in append mode and assign the
20                                                   file handle that is returned to variable $file.
21                   // open password.txt for writing using append mode
22                   if ( !( $file = fopen( "password.txt",
23                      "a" ) ) ) {
24




                                                                                                 2003 Prentice Hall, Inc.
                                                                                              All rights reserved.
25            // print error message and terminate script
                                                                                                                  60
              // execution if file cannot be opened
26
                                                                                             Outline
27           print( "<title>Error</title></head><body>
28             Could not open password file
29             </body></html>" );                                                    password.php
30           die();                           Print an error message and terminate script execution
                                                                                     (2 of 7)
31       }                                    if the file cannot be opened.
32
33       // write username and password to file and
34       // call function userAdded
35       fputs( $file, "$USERNAME,$PASSWORDn" );
36       userAdded( $USERNAME );
37   }
38   else {                  Function userAdded is called to print a message to the
                                  Function fputs writes the name and password to the
39                           user to indicate that the username and password were
                                  text file..
40       // if a new user    added to the file.
                            is not being added, open file
41       // for reading
42       if ( !( $file = fopen( "password.txt",
43           "r" ) ) ) {
44           print( "<title>Error</title></head>
45              <body>Could not open password file
46              </body></html>" );
47            die();
48       }
49



                                                                                       2003 Prentice Hall, Inc.
                                                                                    All rights reserved.
50   $userVerified = 0;
                                                                                                          61
51
                                                                                          Outline
52   // read each line in file and check username
                             Before entering the while      loop, variable
53   // and password   Function fgets reads a lineset to 0. text file.
                                $userVerified is from the
54   while ( !feof(   $file result !$userVerified variable $line.
                       The ) && is assigned to ) {                               password.php
55                                                                               (3 of 7)
56      // read line from file
57
         The while loop executes as long as the there are more
        $line = fgets( Function chop
                        $file, 255 );    removes the newline character
58                       from the and variable $userVerified is
         lines in the file to read end of the line.
          Function split
         still 0 or empty. is called to separate the string at the
59      // remove newline character from end of line
          specified delimiter (in this case, a comma). The
60      $line = chop( $line );
          resulting array usernamein array $fielduser is tested
                      The is stored entered by the .
61
                      against the one returned in the text file (stored
62      // split username and password
                      in the first element of the array). If they match,
63      $field = split( ",", $line, 2 );
                      variable $userVerified is set to 1.
64
65      // verify username
66      if ( $USERNAME == $field[ 0 ] ) {
67         $userVerified = 1;
68
69         // call function checkPassword to If function
                                             verify      checkPassword returns true, function
70         // user’s password                   accessGranted is called to notify the client that
71                                           permission
           if ( checkPassword( $PASSWORD, $field )       has been granted. Otherwise, function
72            == true )                         wrongPassword is called.
73            accessGranted( $USERNAME );
74         else
                                     Function checkPassword is called to verify the
75            wrongPassword();
                                     user’s password. Variable $PASSWORD and array
                                     $field are passed to the function.        2003 Prentice Hall, Inc.
                                                                                 All rights reserved.
76            }
                                                                                                                 62
          }
77
                                                                                            Outline
78                         If variable $userVerified has not been set to a
79        // close text   file          than the while accessDenied is
                           value otherAfter 0, function loop has executed, function
80        fclose( $file   );
                                       fclose is called to close has been
                           called to notify the client that access the file.        password.php
81                         denied.                                                  (4 of 7)
82         // call function accessDenied if username has
83         // not been verified
                                     Function checkPassword compares the user’s
84        if ( !$userVerified )
                                     password to the password in the file. If they match,
85            accessDenied();
                                     true is returned, whereas false is returned if they
86   }
                                     do not.
87
88       // verify user password and return a boolean
89   function checkPassword( $userpassword, $filedata )
90   {
91        if ( $userpassword == $filedata[ 1 ] )
92            return true;
93        else
94            return false;
95   }
96




                                                                                      2003 Prentice Hall, Inc.
                                                                                   All rights reserved.
97        // print a message indicating the user has been added
                                                                                                                      63
      function userAdded( $name )
98
                                                                                                 Outline
99    {
100         print( "<title>Thank You</title></head>
101            <body style = "font-family: userAdded
                                  Function arial;           prints a message to the     password.php
102            font-size: 1em;      client indicating that the user has been added.
                                 color: blue">                                         (5 of 7)
103            <strong>You have been added
104            to the user list, $name.         Function accessGranted prints a
105            <br />Enjoy the                  message to the client indicating that
                                 site.</strong>" );
106   }                                         permission has been granted.
107
108       // print a message indicating permission
109       // has been granted
110   function accessGranted( $name )
111   {
112         print( "<title>Thank You</title></head>
113            <body style = "font-family: arial;
114            font-size: 1em; color: blue">
115            <strong>Permission has been
116            granted, $name. <br />
117            Enjoy the site.</strong>" );
118   }
119




                                                                                           2003 Prentice Hall, Inc.
                                                                                        All rights reserved.
120       // print a message indicating password is invalid
                                                                                                                 64
      function wrongPassword()
121
                                                                                            Outline
122   {
                                        Function wrongPassword prints a message to the
123        print( "<title>Access Denied</title></head>
                                        client indicating that the password is invalid.
124           <body style = "font-family: arial;                                   password.php
125           font-size: 1em; color: red">                                         (6 of 7)
126            <strong>You entered an invalid
127            password.<br />Access has
128           been denied.</strong>" );
129   }
130
131       // print a message indicating access has been denied
132   function accessDenied()
133   {
134        print( "<title>Access Denied</title></head>
135            <body style = "font-family: arial;
136            font-size: 1em; color: red">
137            <strong>
138            You were denied access to this server.
139           <br /></strong>" );          Function accessDenied prints a message to the
140   }                                    client indicating that access has been denied.
141




                                                                                      2003 Prentice Hall, Inc.
                                                                                   All rights reserved.
142               // print a message indicating that fields
                                                                                                                      65
                  // have been left blank
143
                                                     Function fieldsBlank prints a message to Outline the
144           function fieldsBlank()
                                                     client indicating that all form fields have not been
145           {
                                                     completed.
146                print( "<title>Access Denied</title></head>                               password.php
147                   <body style = "font-family: arial;                                    (7 of 7)
148                    font-size: 1em; color: red">
149                    <strong>
150                    Please fill in all form fields.
151                   <br /></strong>" );
152           }
153      ?>
154   </body>
155 </html>




                                                                                           2003 Prentice Hall, Inc.
                                                                                        All rights reserved.
66

         26.6 Verifying a Username and Password
 Fig. 26.16    Verifying a username and password.




2003 Prentice Hall, Inc. All rights reserved.
1   account1,password1
                                                        67
2   account2,password2             Outline
3   account3,password3
4   account4,password4
5   account5,password5    password.txt
6   account6,password6    (1 of 1)
7   account7,password7
8   account8,password8
9   account9,password9
10 account10,password10




                             2003 Prentice Hall, Inc.
                          All rights reserved.
68

                        26.7 Connecting to a Database

    • Databases
           – Store and maintain data
           – MySQL is a free database product
           – PHP supports many database operations
                   • Access databases from Web pages




2003 Prentice Hall, Inc. All rights reserved.
1    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
                                                                                                    69
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
2
                                                                               Outline
3
4    <!-- Fig. 26.18: data.html       -->
5    <!-- Querying a MySQL Database -->                               data.html
6                                                                     (1 of 2)
7    <html xmlns = "http://www.w3.org/1999/xhtml">
8       <head>
9          <title>Sample Database Query</title>
10      </head>
11
12      <body style = "background-color: #F0E68C">
13         <h2 style = "font-family: arial color: blue">
14               Querying a MySQL database.
15         </h2>
16
17         <form method = "post" action = "database.php">
18               <p>Select a field to display:
19
20                  <!-- add a select box containing options -->
21                  <!-- for SELECT query                   -->




                                                                         2003 Prentice Hall, Inc.
                                                                      All rights reserved.
22              <select name = "select">
                                                                                                                     70
                    <option selected = "selected">*</option>
23
                                                                                                Outline
24                  <option>ID</option>
25                  <option>Title</option>      Select box containing options for a SELECT
26                  <option>Category</option>   query.                                  data.html
27                  <option>ISBN</option>                                               (2 of 2)
28              </select>
29           </p>
30
31           <input type = "submit" value = "Send Query"
32              style = "background-color: blue;
33              color: yellow; font-weight: bold" />
34       </form>
35    </body>
36 </html>




                                                                                          2003 Prentice Hall, Inc.
                                                                                       All rights reserved.
71

                        26.7 Connecting to a Database
 Fig. 26.18    Form to query a MySQL database.




2003 Prentice Hall, Inc. All rights reserved.
72

                        26.7 Connecting to a Database

    • Interacting with databases
           – SQL
                   • Structured Query Language
                   • Used to manipulate databases
           – Several useful functions
                   •   mysql_connect
                   •   mysql_select_db
                   •   mysql_query
                   •   mysql_error
                   •   mysql_fetch_row
                   •   mysql_close




2003 Prentice Hall, Inc. All rights reserved.
1    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
                                                                                                                            73
2       "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">                                     Outline
3
4    <!-- Fig. 26.19: database.php          -->
5    <!-- Program to query a database and -->                                                 database.php
6    <!-- send results to the client.       -->                                               (1 of 3)
7
8    <html xmlns = "http://www.w3.org/1999/xhtml">
9       <head>
10         <title>Search Results</title>
11      </head>
12
13      <body style = "font-family: arial, sans-serif"
14         style = "background-color: #F0E68C">
15         <?php             Build the select query and assign the
16                           string to variable $query.
17               extract( $_POST );                   Function mysql_connect returns a database
18                                                    handle which represents PHP’s connection to a
19               // build SELECT query                database. If this connection is not made, function
20               $query = "SELECT " . $select . "   FROM Books";
                                                      die is called to terminate script execution.
21
22               // Connect to MySQL
23               if ( !( $database = mysql_connect( "localhost",
24                  "httpd", "" ) ) )
25                  die( "Could not connect to database" );



                                                                                                 2003 Prentice Hall, Inc.
                                                                                              All rights reserved.
26
                                                                                                                    74
27        // open Products database
                                                                                               Outline
28        if ( !mysql_select_db( "Products", $database )mysql_query
                                               Function )                  returns an object
29                                               containing the result set of the query, which
               die( "Could not open Products database" );
30                                               we assign to variable $result.          database.php
31        //   query Products database                                                   (2 of 3)
32        if   ( !( $result = mysql_query( $query, $database ) ) ) {
                      Function mysql_select_db is called to specify the
33             print( "Could not execute query! <br />" );
                      database to be queried.
34             die( mysql_error() );
35        }
36   ?>
37
38   <h3 style = "color: blue">
39   Search Results</h3>
40
41   <table border = "1" cellpadding = "3" cellspacing = "2"
42        style = "background-color: #ADD8E6">
43
44        <?php                                   The for loop iterates through each
45                                                record in the result set while
46             // fetch each record in result setconstructing an XHTML table from
47             for ( $counter = 0;                the results. Variable $counter is
48                $row = mysql_fetch_row( $result incremented by one for each row
                                                   );
49                $counter++ ){                   retrieved.    Function mysql_fetch_row returns an
50                                                              array containing the elements of each
                                                                row in the result set of our query
                                                                ($result).
                                                                                         2003 Prentice Hall, Inc.
                                                                                      All rights reserved.
51                  // build table to display results
                                                                                                                     75
52                  print( "<tr>" );
                                                                                                Outline
53
54                   foreach ( $row as $key => $value )
55                      print( "<td>$value</td>" );                                      database.php
56                                                                                       (3 of 3)
57                   print( "</tr>" );                The foreach loop iterates through the
58                }
                                                      array containing the elements of each row
59
                                                      and prints out each element in an
60                mysql_close( $databaseThe total number of results are printed to the
                                         );
                                                      individual table cell.
61           ?>                         client.
62
63       </table>
64
65       <br />Your search yielded <strong>
66      <?php print( "$counter" ) ?> results.<br /><br /></strong>
67
68       <h5>Please email comments to
69           <a href = "mailto:deitel@deitel.com">
70                Deitel and Associates, Inc.
71           </a>
72       </h5>
73
74    </body>
75 </html>




                                                                                          2003 Prentice Hall, Inc.
                                                                                       All rights reserved.
76

                        26.7 Connecting to a Database
 Fig. 26.19    Querying a database and displaying the results.




2003 Prentice Hall, Inc. All rights reserved.
77

                                                26.8 Cookies

    • Cookies
           –    Store information on client computer
           –    Track preferences and other information
           –    Stored as text files on hard drive
           –    Never store sensitive information, such as credit card
                numbers, in a cookie
                   • Security risk
    • Cookies and PHP
           – setcookie function
              • Name
              • Value
              • Expiration date


2003 Prentice Hall, Inc. All rights reserved.
1    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
                                                                                                    78
2       "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">             Outline
3
4    <!-- Fig. 26.20: cookies.html -->
5    <!-- Writing a Cookie         -->                                cookies.html
6                                                                     (1 of 2)
7    <html xmlns = "http://www.w3.org/1999/xhtml">
8       <head>
9          <title>Writing a cookie to the client computer</title>
10      </head>
11
12      <body style = "font-family: arial, sans-serif;
13         background-color: #99CCFF">
14
15         <h2>Click Write Cookie to save your cookie data.</h2>
16




                                                                         2003 Prentice Hall, Inc.
                                                                      All rights reserved.
17      <form method = "post" action = "cookies.php"
                                                                                                                    79
                style = "font-size: 10pt">
18
                                                                                               Outline
19           <strong>Name:</strong><br />                   Form data is posted to cookies.php.
20           <input type = "text" name = "NAME" /><br />
21                                                                                    cookies.html
22           <strong>Height:</strong><br />                                           (2 of 2)
23           <input type = "text" name = "HEIGHT" /><br />
24
25           <strong>Favorite Color:</strong><br />
26           <input type = "text" name = "COLOR" /><br />
27
28           <input type = "submit" value = "Write Cookie"
29              style = "background-color: #F0E86C; color: navy;
30              font-weight: bold" /></p>
31       </form>
32    </body>
33 </html>




                                                                                         2003 Prentice Hall, Inc.
                                                                                      All rights reserved.
80

                                                26.8 Cookies
 Fig. 26.20    Gathering data to be written as a cookie.




2003 Prentice Hall, Inc. All rights reserved.
1    <?php
                                                                                                                     81
2       // Fig. 26.21: cookies.php                                                              Outline
3       // Program to write a cookie to a client's machine
4
5       extract( $_POST );                                                             cookies.php
6       // write each form field’s value to a cookie and set the                       (1 of 2)
7       // cookie’s expiration date
8       setcookie( "Name", $NAME, time() + 60 * 60 * 24 * 5 );
9       setcookie( "Height", $HEIGHT, time() + 60 * 60 * 24 * 5 );
10      setcookie( "Color", $COLOR, time() + 60 * 60 * 24 * 5 );
11 ?>                                                    Function setcookie takes the name of the
12                                                       cookie to be set as the first argument,
13   <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" the value to be stored in the
                                                         followed by
14                                                       cookie. The optional third argument specifies
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
15                                                       the expiration date of the cookie.
16 <html xmlns = "http://www.w3.org/1999/xhtml">
17      <head>
18           <title>Cookie Saved</title>
19      </head>
20
21      <body style = "font-family: arial, sans-serif">
22           <p>The cookie has been set with the following data:</p>
23




                                                                                          2003 Prentice Hall, Inc.
                                                                                       All rights reserved.
24      <!-- print each form field’s value -->
                                                                                                                    82
25                                                    Each
         <br /><span style = "color: blue">Name:</span>      form field’s value is printed to Outline
26           <?php print( $NAME ) ?><br />             confirm the data that has been set as a
27                                                     cookie with the user.
28       <span style = "color: blue">Height:</span>                                    cookies.php
29           <?php print( $HEIGHT ) ?><br />                                           (2 of 2)
30
31       <span style = "color: blue">Favorite Color:</span>
32
33       <span style = "color: <?php print( "$COLOR">$COLOR" ) ?>
34       </span><br />
35       <p>Click <a href = "readCookies.php">here</a>
36           to read the saved cookie.</p>
37    </body>
38 </html>
                                                      Hyperlink to readCookies.php.




                                                                                         2003 Prentice Hall, Inc.
                                                                                      All rights reserved.
83

                                                26.8 Cookies
 Fig. 26.21 Writing a cookie to the client.




2003 Prentice Hall, Inc. All rights reserved.
84

                                                26.8 Cookies

    • Reading cookies
           – $_COOKIE environment variable
              • Array
           – foreach loop to access each element
              • Split into key and value




2003 Prentice Hall, Inc. All rights reserved.
85

                                                26.8 Cookies

    • Cookie storage
           – Internet Explorer
                   • Stores cookies in Cookies directory
                   • Text file




2003 Prentice Hall, Inc. All rights reserved.
86

                                                26.8 Cookies
 Fig. 26.22 Cookies directory before a cookie is written.




 Fig. 26.23 Cookies directory after a cookie is written.




2003 Prentice Hall, Inc. All rights reserved.
1    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
                                                                                                    87
2       "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">             Outline
3
4    <!-- Fig. 26.24: readCookies.php                         -->
5    <!-- Program to read cookies from the client's computer -->      readCookies.php
6                                                                     (1 of 2)
7    <html xmlns = "http://www.w3.org/1999/xhtml">
8       <head><title>Read Cookies</title></head>
9
10      <body style = "font-family: arial, sans-serif">
11
12         <p>
13               <strong>
14                 The following data is saved in a cookie on your
15                 computer.
16               </strong>
17         </p>
18




                                                                         2003 Prentice Hall, Inc.
                                                                      All rights reserved.
19       <table border = "5" cellspacing = "0" cellpadding = "10">
                                                                                                                    88
             <?php
20
                                  The foreach loop iterates through the $_COOKIE
                                              PHP creates array $_COOKIE which contains        Outline
21
                                  array and prints the name and value of each cookie
                                              all cookie values indexed by their names.
22                // iterate through array $_COOKIE and print
                                  in an XHTML table.
23                // name and value of each cookie                                      readCookies.php
24                foreach ( $_COOKIE as $key => $value )                                (2 of 2)
25                   print( "<tr>
26                     <td bgcolor="#F0E68C">$key</td>
27                     <td bgcolor="#FFA500">$value</td>
28                     </tr>" );
29           ?>
30
31       </table>
32    </body>
33 </html>




                                                                                         2003 Prentice Hall, Inc.
                                                                                      All rights reserved.
89

                                                26.8 Cookies
 Fig. 26.24 Displaying the cookie’s content.




2003 Prentice Hall, Inc. All rights reserved.
90

                          26.9 Dynamic Content in PHP

    • Dynamically alter XHTML content
           – Form’s action property set to same page that contains it
           – Perform different actions when page is loaded and form is
             submitted
                   • isset variable
           – Check for errors
                   • Write different XHTML when errors encountered
           – $$variable syntax
              • References variable whose name equals the value of $variable
           – If input is valid, make MySQL database calls




2003 Prentice Hall, Inc. All rights reserved.
Php NotesBeginner
Php NotesBeginner
Php NotesBeginner
Php NotesBeginner
Php NotesBeginner
Php NotesBeginner
Php NotesBeginner
Php NotesBeginner
Php NotesBeginner
Php NotesBeginner
Php NotesBeginner
Php NotesBeginner
Php NotesBeginner
Php NotesBeginner
Php NotesBeginner
Php NotesBeginner
Php NotesBeginner

Contenu connexe

Tendances

JSON-RPC Proxy Generation with PHP 5
JSON-RPC Proxy Generation with PHP 5JSON-RPC Proxy Generation with PHP 5
JSON-RPC Proxy Generation with PHP 5
Stephan Schmidt
 
Tutorial de forms 10g
Tutorial de forms 10gTutorial de forms 10g
Tutorial de forms 10g
miguel
 
Lions本読書会合宿成果発表
Lions本読書会合宿成果発表Lions本読書会合宿成果発表
Lions本読書会合宿成果発表
Ryousei Takano
 

Tendances (20)

API
APIAPI
API
 
Hyperledger 구조 분석
Hyperledger 구조 분석Hyperledger 구조 분석
Hyperledger 구조 분석
 
jstl ( jsp standard tag library )
jstl ( jsp standard tag library )jstl ( jsp standard tag library )
jstl ( jsp standard tag library )
 
06 再利用のためのインクルードとクラス
06 再利用のためのインクルードとクラス06 再利用のためのインクルードとクラス
06 再利用のためのインクルードとクラス
 
Unicode (UTF-8) with PHP 5.3, MySQL 5.5 and HTML5 Cheat Sheet (2011)
Unicode (UTF-8) with PHP 5.3, MySQL 5.5 and HTML5 Cheat Sheet (2011)Unicode (UTF-8) with PHP 5.3, MySQL 5.5 and HTML5 Cheat Sheet (2011)
Unicode (UTF-8) with PHP 5.3, MySQL 5.5 and HTML5 Cheat Sheet (2011)
 
Effective CMake
Effective CMakeEffective CMake
Effective CMake
 
JSON-RPC Proxy Generation with PHP 5
JSON-RPC Proxy Generation with PHP 5JSON-RPC Proxy Generation with PHP 5
JSON-RPC Proxy Generation with PHP 5
 
Tutorial de forms 10g
Tutorial de forms 10gTutorial de forms 10g
Tutorial de forms 10g
 
DBMS_SQL
DBMS_SQLDBMS_SQL
DBMS_SQL
 
05 再利用のためのインクルード
05 再利用のためのインクルード05 再利用のためのインクルード
05 再利用のためのインクルード
 
Odoo command line interface
Odoo command line interfaceOdoo command line interface
Odoo command line interface
 
The beautyandthebeast phpbat2010
The beautyandthebeast phpbat2010The beautyandthebeast phpbat2010
The beautyandthebeast phpbat2010
 
Lions本読書会合宿成果発表
Lions本読書会合宿成果発表Lions本読書会合宿成果発表
Lions本読書会合宿成果発表
 
Php
PhpPhp
Php
 
CMake Tutorial
CMake TutorialCMake Tutorial
CMake Tutorial
 
Php
PhpPhp
Php
 
Using SPMetal for faster SharePoint development
Using SPMetal for faster SharePoint developmentUsing SPMetal for faster SharePoint development
Using SPMetal for faster SharePoint development
 
Unit 1-introduction to perl
Unit 1-introduction to perlUnit 1-introduction to perl
Unit 1-introduction to perl
 
WEB PROGRAMMING UNIT VI BY BHAVSINGH MALOTH
WEB PROGRAMMING UNIT VI BY BHAVSINGH MALOTHWEB PROGRAMMING UNIT VI BY BHAVSINGH MALOTH
WEB PROGRAMMING UNIT VI BY BHAVSINGH MALOTH
 
CMake - Introduction and best practices
CMake - Introduction and best practicesCMake - Introduction and best practices
CMake - Introduction and best practices
 

En vedette (6)

Introduction to JSP
Introduction to JSPIntroduction to JSP
Introduction to JSP
 
Java server pages
Java server pagesJava server pages
Java server pages
 
Java Server Pages
Java Server PagesJava Server Pages
Java Server Pages
 
Jsp And Jdbc
Jsp And JdbcJsp And Jdbc
Jsp And Jdbc
 
Java lezione 10
Java lezione 10Java lezione 10
Java lezione 10
 
What is PHP?
What is PHP?What is PHP?
What is PHP?
 

Similaire à Php NotesBeginner

Tips
TipsTips
Tips
mclee
 

Similaire à Php NotesBeginner (20)

Php 26
Php 26Php 26
Php 26
 
Php 26
Php 26Php 26
Php 26
 
Synapse india basic php development part 1
Synapse india basic php development part 1Synapse india basic php development part 1
Synapse india basic php development part 1
 
Synapse india complain sharing info about php chaptr 26
Synapse india complain sharing info about php chaptr 26Synapse india complain sharing info about php chaptr 26
Synapse india complain sharing info about php chaptr 26
 
Sql php-vibrant course-mumbai(1)
Sql php-vibrant course-mumbai(1)Sql php-vibrant course-mumbai(1)
Sql php-vibrant course-mumbai(1)
 
Php manish
Php manishPhp manish
Php manish
 
Php classes in mumbai
Php classes in mumbaiPhp classes in mumbai
Php classes in mumbai
 
Tips
TipsTips
Tips
 
php&mysql with Ethical Hacking
php&mysql with Ethical Hackingphp&mysql with Ethical Hacking
php&mysql with Ethical Hacking
 
Php training100%placement-in-mumbai
Php training100%placement-in-mumbaiPhp training100%placement-in-mumbai
Php training100%placement-in-mumbai
 
PHP Course (Basic to Advance)
PHP Course (Basic to Advance)PHP Course (Basic to Advance)
PHP Course (Basic to Advance)
 
Day1
Day1Day1
Day1
 
Basics PHP
Basics PHPBasics PHP
Basics PHP
 
PHP Scripting
PHP ScriptingPHP Scripting
PHP Scripting
 
PHP from soup to nuts Course Deck
PHP from soup to nuts Course DeckPHP from soup to nuts Course Deck
PHP from soup to nuts Course Deck
 
PHP - Intriduction to MySQL And PHP
PHP - Intriduction to MySQL And PHPPHP - Intriduction to MySQL And PHP
PHP - Intriduction to MySQL And PHP
 
Introduction to web and php mysql
Introduction to web and php mysqlIntroduction to web and php mysql
Introduction to web and php mysql
 
Processing massive amount of data with Map Reduce using Apache Hadoop - Indi...
Processing massive amount of data with Map Reduce using Apache Hadoop  - Indi...Processing massive amount of data with Map Reduce using Apache Hadoop  - Indi...
Processing massive amount of data with Map Reduce using Apache Hadoop - Indi...
 
Php Tutorial
Php TutorialPhp Tutorial
Php Tutorial
 
Php i basic chapter 3
Php i basic chapter 3Php i basic chapter 3
Php i basic chapter 3
 

Dernier

Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
ZurliaSoop
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
QucHHunhnh
 
Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please Practise
AnaAcapella
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
heathfieldcps1
 

Dernier (20)

Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
Spatium Project Simulation student brief
Spatium Project Simulation student briefSpatium Project Simulation student brief
Spatium Project Simulation student brief
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
Magic bus Group work1and 2 (Team 3).pptx
Magic bus Group work1and 2 (Team 3).pptxMagic bus Group work1and 2 (Team 3).pptx
Magic bus Group work1and 2 (Team 3).pptx
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
Asian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptxAsian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptx
 
Third Battle of Panipat detailed notes.pptx
Third Battle of Panipat detailed notes.pptxThird Battle of Panipat detailed notes.pptx
Third Battle of Panipat detailed notes.pptx
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docx
 
Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please Practise
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docx
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 

Php NotesBeginner

  • 1. 1 PHP Notes Outline 26.1 Introduction 26.2 PHP 26.3 String Processing and Regular Expressions 26.4 Viewing Client/Server Environment Variables 26.5 Form Processing and Business Logic 26.6 Verifying a Username and Password 26.7 Connecting to a Database 26.8 Cookies 26.9 Dynamic Content in PHP 26.10 Operator Precedence 26.11 Web Resources 2003 Prentice Hall, Inc. All rights reserved.
  • 2. 2 Objectives In this chapter, you will learn: – To understand PHP data types, operators, arrays and control structures. – To understand string processing and regular expressions in PHP. – To construct programs that process form data. – To be able to read and write client data using cookies. – To construct programs that interact with MySQL databases. 2003 Prentice Hall, Inc. All rights reserved.
  • 3. 3 26.1 Introduction • PHP – PHP: Hypertext Preprocessor – Originally called “Personal Home Page Tools” – Popular server-side scripting technology – Open-source • Anyone may view, modify and redistribute source code • Supported freely by community – Platform independent 2003 Prentice Hall, Inc. All rights reserved.
  • 4. 4 26.2 PHP • Basic application – Scripting delimiters • <? php ?> • Must enclose all script code – Variables preceded by $ symbol • Case-sensitive – End statements with semicolon – Comments • // for single line • /* */ for multiline – Filenames end with .php by convention 2003 Prentice Hall, Inc. All rights reserved.
  • 5. 1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 5 2 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> Outline 3 4 <!-- Fig. 26.1: first.php --> 5 <!-- Our first PHP script --> first.php 6 Scripting delimiters (1 of 1) 7 <?php 8 $name = "LunaTic"; // declaration 9 ?> Declare variable $name 10 11 <html xmlns = "http://www.w3.org/1999/xhtml"> 12 <head> 13 <title>A simple PHP document</title>Single-line comment 14 </head> 15 16 <body style = "font-size: 2em"> 17 <p> 18 <strong> 19 20 <!-- print variable name’s value --> 21 Welcome to PHP, <?php print( "$name" ); ?>! 22 </strong> 23 </p> 24 </body> Function print outputs the value of variable $name 25 </html> 2003 Prentice Hall, Inc. All rights reserved.
  • 6. 6 26.2 PHP Fig. 26.1 Simple PHP program. 2003 Prentice Hall, Inc. All rights reserved.
  • 7. 7 26.2 PHP • Variables – Can have different types at different times – Variable names inside strings replaced by their value – Type conversions • settype function • Type casting – Concatenation operator • . (period) • Combine strings 2003 Prentice Hall, Inc. All rights reserved.
  • 8. 8 26.2 PHP Data type Description int, integer Whole numbers (i.e., numbers without a decimal point). float, double Real numbers (i.e., numbers containing a decimal point). string Text enclosed in either single ('') or double ("") quotes. bool, Boolean True or false. array Group of elements of the same type. object Group of associated data and methods. Resource An external data source. NULL No value. Fig. 26.2 PHP data types. 2003 Prentice Hall, Inc. All rights reserved.
  • 9. 1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 9 2 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> Outline 3 4 <!-- Fig. 26.3: data.php --> 5 <!-- Demonstration of PHP data types --> data.php 6 (1 of 3) 7 <html xmlns = "http://www.w3.org/1999/xhtml"> 8 <head> 9 <title>PHP data types</title> 10 </head> 11 12 <body> 13 14 <?php Assign a string to variable 15 $testString 16 // declare a string, double and integer 17 $testString = "3.5 seconds"; 18 $testDouble = 79.2; Assign a double to variable $testDouble Assign an integer to variable 19 $testInteger = 12; $testInteger 20 ?> 21 2003 Prentice Hall, Inc. All rights reserved.
  • 10. 22 <!-- print each variable’s value --> 10 <?php print( $testString ); ?> is a string.<br /> 23 Outline 24 <?php print( $testDouble ); ?> is a double.<br /> 25 <?php print( $testInteger ); ?> is an integer.<br /> 26 data.php 27 <br /> Print each variable’s (2 of 3) value 28 Now, converting to other types:<br /> 29 <?php 30 31 // call function settype to convert variable 32 // testString to different data types 33 print( "$testString" ); 34 settype( $testString, "double" ); 35 print( " as a double is $testString <br />" ); 36 print( "$testString" ); 37 settype( $testString, "integer" ); 38 print( " as an integer is $testString <br />" ); 39 settype( $testString, "string" ); 40 Call function settype print( "Converting back to a string results in to 41 $testString <br /><brfunction settypetype of Call />" ); the data to convert 42 variable $testString to a convert the data type of 43 $data = "98.6 degrees"; double. variable $testString to an integer. Convert variable $testString back to a string 2003 Prentice Hall, Inc. All rights reserved.
  • 11. 44 11 // use type casting to cast variables to a 45 Outline 46 // different type 47 print ( "Now using type casting instead: <br /> 48 As a string - " . ( string ) $data . data.php 49 "<br />As a double - " . (double ) $data . (3 of 3) 50 "<br />As an integer - " . ( integer ) $data ); 51 ?> Use type casting to cast variable 52 </body> $data to different types 53 </html> 2003 Prentice Hall, Inc. All rights reserved.
  • 12. 12 26.2 PHP Fig. 26.3 Type conversion. 2003 Prentice Hall, Inc. All rights reserved.
  • 13. 13 26.2 PHP • Arithmetic operators – Assignment operators • Syntactical shortcuts • Before being assigned values, variables have value undef • Constants – Named values – define function 2003 Prentice Hall, Inc. All rights reserved.
  • 14. 1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 14 2 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> Outline 3 4 <!-- Fig. 26.4: operators.php --> 5 <!-- Demonstration of operators --> operators.php 6 (1 of 3) 7 <html xmlns = "http://www.w3.org/1999/xhtml"> 8 <head> 9 <title>Using arithmetic operators</title> 10 </head> 11 12 <body> 13 <?php 14 $a = 5; Define constant VALUE. 15 print( "The value of variable a is $a <br />" ); 16 17 // define constant VALUE Add constant VALUE to variable $a. 18 define( "VALUE", 5 ); 19 20 // add constant VALUE to variable $a 21 $a = $a + VALUE; 22 print( "Variable a after adding constant VALUE 23 is $a <br />" ); 24 2003 Prentice Hall, Inc. All rights reserved.
  • 15. 25 // multiply variable $a by 2 15 $a *= 2; 26 Multiply variable $a by two using the Outline 27 print( "Multiplying variable a by 2 yields $a <br />" ); multiplication assignment operator *=. 28 29 // test if variable $a is less than 50 operators.php Test than 50 variable $a is less than 50 Print if variable $a is lesswhether . 30 if ( $a < 50 ) (2 of 3) 31 print( "Variable a is less than 50 <br />" ); 32 33 // add 40 to variable $a Add 40 to variable $a using the addition assignment 34 $a += 40; operator +=. 35 print( "Variable a after adding 40 is $a <br />" ); 36 37 // test if variable $a is 50 or less 38 if ( $a < 51 ) 39 print( "Variable a is still 50 or less<br />" ); 40 41 // test if variable $a is between 50 and 100, inclusive 42 elseif ( $a < 101 ) 43 print( "Variable a is now between 50 and 100, 44 inclusive<br />" ); 45 else 46 print( "Variable a is now greater than 100 47 <br />" ); 48 2003 Prentice Hall, Inc. All rights reserved.
  • 16. 49 // print an uninitialized variable 16 50 print( "Using a variable before initializing: Outline 51 $nothing <br />" ); 52 53 // add constant VALUE to an uninitialized variable operators.php 54 $test = $num + VALUE; (3 of 3) 55 print( "An uninitialized variable plus constant 56 VALUE yields $test <br />" ); 57 Print an uninitializedVALUE to ($nothing). Add constant variable an uninitialized 58 // add a string to an integer variable. 59 $str = "3 dollars"; 60 $a += $str; 61 print( "Adding a string to variable a yields $a 62 <br />" ); 63 ?> 64 </body> Add a string to an integer. 65 </html> 2003 Prentice Hall, Inc. All rights reserved.
  • 17. 17 26.2 PHP Fig. 26.4 Using PHP’s arithmetic operators. 2003 Prentice Hall, Inc. All rights reserved.
  • 18. 18 26.2 PHP • Keywords – Reserved for language features – if…elseif…else • Arrays – Group of related data • Elements – Name plus braces and index • Indices start at zero – count function – array function 2003 Prentice Hall, Inc. All rights reserved.
  • 19. 19 26.2 PHP • Arrays, cont. – Built-in iterators • Maintain pointer to element currently referenced • reset • key • next • foreach loops 2003 Prentice Hall, Inc. All rights reserved.
  • 20. 20 26.2 PHP PHP keywords and do for include require true break else foreach list return var case elseif function new static virtual class extends global not switch xor continue false if or this while default Fig. 26.5 PHP keywords. 2003 Prentice Hall, Inc. All rights reserved.
  • 21. 1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 21 2 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> Outline 3 4 <!-- Fig. 26.6: arrays.php --> 5 <!-- Array manipulation --> arrays.php 6 (1 of 3) 7 <html xmlns = "http://www.w3.org/1999/xhtml"> 8 <head> 9 <title>Array manipulation</title> 10 </head> 11 12 <body> 13 <?php Create the array $first by assigning a value 14 to an array element. 15 // create array first 16 print( "<strong>Creating the first array</strong> 17 <br />" ); 18 $first[ 0 ] = "zero"; 19 $first[ 1 ] = Assign "one"; a value to the array, omitting the index. 20 $first[ 2 ] = Appends a Use a for loop to print outthe array. "two"; new element to the end of each element’s index and value. 21 $first[] = "three"; Function count returns the total number of elements in the 22 array. 23 // print each element’s index and value 24 for ( $i = 0; $i < count( $first ); $i++ ) 25 print( "Element $i is $first[$i] <br />" ); 2003 Prentice Hall, Inc. All rights reserved.
  • 22. 26 22 print( "<br /><strong>Creating the second array 27 Outline Call function array to create an array that contains 28 </strong><br />" ); 29 the arguments passed to it. Store the array in variable 30 // call function $second array to create array second . arrays.php 31 $second = array( "zero", "one", "two", "three" ); (2 of 3) 32 for ( $i = 0; $i < count( $second ); $i++ ) 33 print( "Element $i is $second[$i] <br />" ); 34 35 print( "<br /><strong>Creating the third array 36 </strong><br />" ); 37 38 // assign values to non-numerical indices 39 $third[ "ArtTic" ] = 21; Assign values to non-numerical indices 40 $third[ "LunaTic" ] = 18; in array $third. 41 $third[ "GalAnt" ] = 23; Function reset sets the internal pointer to the 42 first element of the array. 43 // iterate through the array elements and print each 44 // element’s name and value 45 for ( reset( $third ); $element = key( $third ); 46 next( $third ) ) 47 print( "$element is $third[$element] <br />" ); 48 Function key returns the index of the element which the internal pointer references. Function next moves the internal pointer to the next element. 2003 Prentice Hall, Inc. All rights reserved.
  • 23. 49 print( "<br /><strong>Creating the fourth array 23 </strong><br />" ); 50 Outline 51 52 // call function array to create array fourth using 53 // string indices arrays.php 54 $fourth = array( (3 of 3) 55 "January" => "first", "February" => "second", 56 "March" => "third", "April" => "fourth", 57 "May" => "fifth", Operator =>=> used in function array to assign each "June" is "sixth", 58 "July" => "seventh", "August" string index. The value to the left of the element a => "eighth", 59 "September" => "ninth", operator is the array index, and the value to the right is "October" => "tenth", 60 "November" => the element’s value. "eleventh","December" => "twelfth" 61 ); 62 63 // print each element’s name and value 64 foreach ( $fourth as $element => $value ) 65 print( "$element is the $value month <br />" ); 66 ?> 67 </body> 68 </html> 2003 Prentice Hall, Inc. All rights reserved.
  • 24. 24 26.2 PHP Fig. 26.6 Array manipulation. 2003 Prentice Hall, Inc. All rights reserved.
  • 25. 25 26.3 String Processing and Regular Expressions • String processing – Equality and comparison two important operations – strcmp function • Returns –1 if string 1 < string 2 • Returns 0 if string 1 = string 2 • Returns 1 if string 1 > string 2 – Relational operators 2003 Prentice Hall, Inc. All rights reserved.
  • 26. 1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 26 2 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> Outline 3 4 <!-- Fig. 26.7: compare.php --> 5 <!-- String Comparison --> compare.php 6 (1 of 2) 7 <html xmlns = "http://www.w3.org/1999/xhtml"> 8 <head> 9 <title>String Comparison</title> 10 </head> 11 12 <body> 13 <?php Use a for loop to iterate through each array element. 14 15 // create array fruits 16 $fruits = array( "apple", "orange", "banana" ); Function strcmp compares two strings. If the first string 17 alphabetically precedes the second, then –1 is returned. If 18 // iterate through each array element the strings are equal, 0 is returned. If the first string 19 for ( $i = 0; $i < count( $fruits ); $i++ ) { alphabetically follows the second, then 1 is returned. 20 21 // call function strcmp to compare the array element 22 // to string "banana" 23 if ( strcmp( $fruits[ $i ], "banana" ) < 0 ) 24 print( $fruits[ $i ]." is less than banana " ); 2003 Prentice Hall, Inc. All rights reserved.
  • 27. 25 elseif ( strcmp( $fruits[ $i ], "banana" ) > 0 ) 27 print( $fruits[ $i ]. 26 Outline 27 " is greater than banana " ); 28 else 29 print( $fruits[ $i ]." is Use relational operators equal to banana " ); to compare each array compare.php 30 element to string “apple”. (2 of 2) 31 // use relational operators to compare each element 32 // to string "apple" 33 if ( $fruits[ $i ] < "apple" ) 34 print( "and less than apple! <br />" ); 35 elseif ( $fruits[ $i ] > "apple" ) 36 print( "and greater than apple! <br />" ); 37 elseif ( $fruits[ $i ] == "apple" ) 38 print( "and equal to apple! <br />" ); 39 40 } 41 ?> 42 </body> 43 </html> 2003 Prentice Hall, Inc. All rights reserved.
  • 28. 28 26.3 String Processing and Regular Expressions Fig. 26.7 Using the string comparison operators. 2003 Prentice Hall, Inc. All rights reserved.
  • 29. 29 26.3 String Processing and Regular Expressions • Regular expressions – Pattern matching templates – ereg function • POSIX – preg_match function • Perl – ereg_replace function • Building regular expressions – Metacharacters • $, ., ^ – Brackets [ ] 2003 Prentice Hall, Inc. All rights reserved.
  • 30. 1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 30 2 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> Outline 3 4 <!-- Fig. 26.8: expression.php --> 5 <!-- Using regular expressions --> expression.php 6 (1 of 3) 7 <html xmlns = "http://www.w3.org/1999/xhtml"> 8 <head> 9 <title>Regular expressions</title> 10 </head> 11 12 <body> 13 <?php Function ereg searches for the literal 14 $search = "Now is the characters Now inside variable $search. time"; 15 print( "Test string is: '$search'<br /><br />" ); 16 17 // call function ereg to search for pattern 'Now' 18 // in variable search 19 if ( ereg( "Now", $search ) ) 20 print( "String 'Now' was found.<br />" ); 21 2003 Prentice Hall, Inc. All rights reserved.
  • 31. 22 // search for pattern 'Now' in the beginning of 31 // the string 23 Outline 24 if ( ereg( "^Now", $search ) ) The dollar sign special character ($) search for the 25 print( "String 'Now' found at beginning pattern Now (^) matches the The caret special character at the end of the string. 26 of the line.<br />" ); expression.php 27 beginning of a string. Function ereg searches the (2 of 3) 28 // beginning ofthe end of for pattern Now . search for pattern 'Now' at the string the string 29 if ( ereg( "Now$", $search ) ) 30 print( "String 'Now' was found at the end 31 of the line.<br />" ); 32 33 // search for any word ending in 'ow' 34 if ( ereg( "[[:<:]]([a-zA-Z]*ow)[[:>:]]", $search, 35 $match ) ) 36 print( "Word found ending in 'ow': " . 37 $match[ 1 ] . "<br />" ); 38 The special bracket parentheses, [a-zA-Z]*ow The expression inside the expressions [[:<:]] and , 39 // search for any words beginning with 't' Placing a word in the in ow. The quantifier * matches anypatternending beginning and end of a [[:>:]] match parentheses stores the matched 40 print( "Words beginning with 't' found: "); 41 word, preceding pattern 0 or more times. matches in the array that is specified in the third argument string therespectively. to function ereg. 42 while ( eregi( "[[:<:]](t[[:alpha:]]+)[[:>:]]", 43 $search, $match ) ) { 44 print( $match[ 1 ] . " " ); The pattern used in this example, 45 [[:<:]](t[[:alpha:]]+)[[:>:]], matches any The while word is used to find each occurrence of a loop beginning with the Function eregi is used to specify case character t followed by one or insensitive string beginning with t. word in themore characters. Character class [[:alpha:]] pattern matches. recognizes any alphabetic character. 2003 Prentice Hall, Inc. All rights reserved.
  • 32. 46 // remove the first occurrence of a word beginning 32 // with 't' to find other instances in the string 47 Outline 48 $search = ereg_replace( $match[ 1 ], "", $search ); 49 } 50 expression.php After printing a match of a word beginning with t, function 51 print( "<br />" ); ereg_replace is called to remove the word from the of 3) (3 string. 52 ?> This is necessary be because to find multiple instances of a 53 </body> given pattern, the first matched instance must first be removed. 54 </html> Function ereg_replace takes three arguments: the pattern to match, a string to replace the matched string and the string to search. 2003 Prentice Hall, Inc. All rights reserved.
  • 33. 33 26.3 String Processing and Regular Expressions Fig. 26.8 Regular expressions in PHP. 2003 Prentice Hall, Inc. All rights reserved.
  • 34. 34 26.3 String Processing and Regular Expressions Quantifier Matches {n} Exactly n times. {m,n} Between m and n times inclusive. {n,} n or more times. + One or more times (same as {1,}). * Zero or more times (same as {0,}). ? Zero or one time (same as {0,1}). Fig. 26.9 Some PHP quantifiers. 2003 Prentice Hall, Inc. All rights reserved.
  • 35. 35 26.3 String Processing and Regular Expressions Character class Description alnum Alphanumeric characters (i.e., letters [a-zA-Z] or digits [0-9]). alpha Word characters (i.e., letters [a-zA-Z]). digit Digits. space Whitespace. lower Lowercase letters. upper Uppercase letters. Fig. 26.10 Some PHP character classes. 2003 Prentice Hall, Inc. All rights reserved.
  • 36. 36 26.4 Viewing Client/Server Environment Variables • Environment variables – Provide information about execution environment • Type of Web browser • Type of server • Details of HTTP connection – Stored as array in PHP • $_ENV 2003 Prentice Hall, Inc. All rights reserved.
  • 37. 37 26.4 Viewing Client/Server Environment Variables Variable name Description $_SERVER Data about the currently running server. $_ENV Data about the client’s environment. $_GET Data posted to the server by the get method. $_POST Data posted to the server by the post method. $_COOKIE Data contained in cookies on the client’s computer. $GLOBALS Array containing all global variables. Fig. 26.11 Some useful global arrays. 2003 Prentice Hall, Inc. All rights reserved.
  • 38. 1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 38 2 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> Outline 3 4 <!-- Fig. 26.11: env.php --> 5 <!-- Program to display environment variables --> env.php 6 (1 of 1) 7 <html xmlns = "http://www.w3.org/1999/xhtml"> 8 <head> 9 <title>Environment Variables</title> 10 </head> 11 12 <body> 13 <table border = "0" cellpadding = "2" cellspacing = "0" 14 width = "100%"> 15 <?php 16 17 // print the key and value for each element 18 // in the $_ENV array 19 foreach ( $_ENV as $key => $value ) 20 print( "<tr><td bgcolor = "#11bbff"> 21 The foreach loop <strong>$key</strong></td> is used to print out the keys and 22 <td>$value</td></tr>"each element in the $_ENV array. values for ); 23 ?> PHP stores environment variables and their values in 24 </table> the $_ENV array. 25 </body> 26 </html> 2003 Prentice Hall, Inc. All rights reserved.
  • 39. 39 26.4 Viewing Client/Server Environment Variables Fig. 26.12 Displaying environment variables. 2003 Prentice Hall, Inc. All rights reserved.
  • 40. 40 26.5 Form Processing and Business Logic • Form processing – action property • Where to send form data – method property • post – Each element has unique name 2003 Prentice Hall, Inc. All rights reserved.
  • 41. 1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 41 2 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> Outline 3 4 <!-- Fig. 26.13: form.html --> 5 <!-- Form for use with the form.php program --> form.html 6 (1 of 4) 7 <html xmlns = "http://www.w3.org/1999/xhtml"> 8 <head> 9 <title>Sample form to take user input in XHTML</title> 10 </head> 11 12 <body> 13 The action attribute of the form element 14 <h1>This is indicates that when the user clicks Register, the a sample registration form.</h1> 15 Please fill in all fields and click Register. posted to form.php. form data will be 16 17 <!-- post form data to form.php --> 18 <form method = "post" action = "form.php"> 19 <img src = "images/user.gif" alt = "User" /><br /> 20 <span style = "color: blue"> 21 Please fill out the fields below.<br /> 22 </span> 23 2003 Prentice Hall, Inc. All rights reserved.
  • 42. 24 <!-- create four text boxes for user input --> 42 <img src = "images/fname.gif" alt = "First Name" /> 25 A unique name (e.g., email) is assigned to each Outline <input type = "text" name = "fname" /><br /> 26 of the form’s input fields. When Register is 27 clicked, each field’s name and value are sent to 28 <img src = "images/lname.gif" alt = "Last Name" /> the Web server. form.html 29 <input type = "text" name = "lname" /><br /> (2 of 4) 30 31 <img src = "images/email.gif" alt = "Email" /> 32 <input type = "text" name = "email" /><br /> 33 34 <img src = "images/phone.gif" alt = "Phone" /> 35 <input type = "text" name = "phone" /><br /> 36 37 <span style = "font-size: 10pt"> 38 Must be in the form (555)555-5555</span> 39 <br /><br /> 40 41 <img src = "images/downloads.gif" 42 alt = "Publications" /><br /> 43 44 <span style = "color: blue"> 45 Which book would you like information about? 46 </span><br /> 47 2003 Prentice Hall, Inc. All rights reserved.
  • 43. 48 <!-- create drop-down list containing book names --> 43 <select name = "book"> 49 Outline 50 <option>Internet and WWW How to Program 3e</option> 51 <option>C++ How to Program 4e</option> 52 <option>Java How to Program 5e</option> form.html 53 <option>XML How to Program 1e</option> (3 of 4) 54 </select> 55 <br /><br /> 56 57 <img src = "images/os.gif" alt = "Operating System" /> 58 <br /><span style = "color: blue"> 59 Which operating system are you currently using? 60 <br /></span> 61 62 <!-- create five radio buttons --> 63 <input type = "radio" name = "os" value = "Windows XP" 64 checked = "checked" /> 65 Windows XP 66 67 <input type = "radio" name = "os" value = 68 "Windows 2000" /> 69 Windows 2000 70 71 <input type = "radio" name = "os" value = 72 "Windows 98" /> 73 Windows 98<br /> 2003 Prentice Hall, Inc. All rights reserved.
  • 44. 74 44 <input type = "radio" name = "os" value = "Linux" /> 75 Outline 76 Linux 77 78 <input type = "radio" name = "os" value = "Other" /> form.html 79 Other<br /> (4 of 4) 80 81 <!-- create a submit button --> 82 <input type = "submit" value = "Register" /> 83 </form> 84 85 </body> 86 </html> 2003 Prentice Hall, Inc. All rights reserved.
  • 45. 45 26.5 Form Processing and Business Logic Fig. 26.13 XHTML form for gathering user input. 2003 Prentice Hall, Inc. All rights reserved.
  • 46. 46 26.5 Form Processing and Business Logic • Business logic – Confirm that valid information was entered – extract function • Creates variables corresponding to each key-value pair in array • Easily retrieve all values sent to PHP page – Regular expressions very helpful – Do checks on client side where possible • JavaScript • Conserves server resources • Ending a script – die function • Remember to close all HTML tags 2003 Prentice Hall, Inc. All rights reserved.
  • 47. 1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 47 2 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> Outline 3 4 <!-- Fig. 26.14: form.php --> 5 <!-- Read information sent from form.html --> form.php 6 (1 of 4) 7 <html xmlns = "http://www.w3.org/1999/xhtml"> 8 <head> 9 <title>Form Validation</title> 10 </head> 11 12 <body style = "font-family: arial,sans-serif"> Function ereg is called to determine whether the 13 The parentheses in the expression must be 14 <?php phone number entered by the user is valid. three digits ([0-9]{3}), a the opening followed by The expression ( matches closing 15 extract( $_POST ); parenthesis, parentheses ofliteral hyphen and three digits, a a phone number. 16 four additional digits. 17 // determine whether phone number is valid and print 18 // an error message if not 19 if ( !ereg( "^([0-9]{3})[0-9]{3}-[0-9]{4}$", 20 $phone ) ){ 21 We access the phone field’s value from form.html by using variable $phone. 2003 Prentice Hall, Inc. All rights reserved.
  • 48. 22 print( "<p><span style = "color: red; 48 font-size: 2em"> 23 Outline 24 INVALID PHONE NUMBER</span><br /> 25 A valid phone number must be in the form 26 <strong>(555)555-5555</strong><br /> form.php 27 <span style = "color: blue"> (2 of 4) 28 Click the Back button, enter a valid phone Function die terminates script execution 29 number and resubmit.<br /><br /> 30 Thank You.</span></p></body></html>" ); 31 32 die(); // terminate script execution 33 } 34 ?> 35 36 <p>Hi 37 <span style = "color: blue"> 38 <strong> 39 <?php print( "$fname" ); ?> 40 </strong> 41 </span>. 42 Thank you for completing the survey.<br /> 43 2003 Prentice Hall, Inc. All rights reserved.
  • 49. 44 You have been added to the 49 <span style = "color: blue"> 45 Outline 46 <strong> 47 <?php print( "$book " ); ?> 48 </strong> form.php 49 </span> (3 of 4) 50 mailing list. 51 </p> 52 <strong>The following information has been saved 53 in our database:</strong><br /> 54 55 <table border = "0" cellpadding = "0" cellspacing = "10"> 56 <tr> 57 <td bgcolor = "#ffffaa">Name </td> 58 <td bgcolor = "#ffffbb">Email</td> 59 <td bgcolor = "#ffffcc">Phone</td> 60 <td bgcolor = "#ffffdd">OS</td> 61 </tr> 62 63 <tr> 64 <?php 65 2003 Prentice Hall, Inc. All rights reserved.
  • 50. 66 // print each form field’s value 50 print( "<td>$fname $lname</td> 67 Outline 68 <td>$email</td> 69 <td>$phone</td> 70 <td>$os</td>" ); form.php 71 ?> (4 of 4) 72 </tr> 73 </table> 74 75 <br /><br /><br /> 76 <div style = "font-size: 10pt; text-align: center"> 77 This is only a sample form. 78 You have not been added to a mailing list. 79 </div> 80 </body> 81 </html> 2003 Prentice Hall, Inc. All rights reserved.
  • 51. 51 26.5 Form Processing and Business Logic Fig. 26.14 Obtaining user input through forms. 2003 Prentice Hall, Inc. All rights reserved.
  • 52. 52 26.6 Verifying a Username and Password • Private website – Only accessible to certain individuals – Encrypt username and password data when sending, storing and retrieving for increased security • Implementing password checking – Login information stored in file • fopen function • Read, write, append modes – Store data using fputs • n newline character – Close files when done • fclose function 2003 Prentice Hall, Inc. All rights reserved.
  • 53. 53 26.6 Verifying a Username and Password • Implementing password checking, cont. – Trim newline character • chop function – Split string into substrings given a certain delimiter • split function – If username/password match list, allow access 2003 Prentice Hall, Inc. All rights reserved.
  • 54. 1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 54 2 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> Outline 3 4 <!-- Fig. 26.15: password.html --> 5 <!-- XHTML form sent to password.php for verification --> password.html 6 (1 of 4) 7 <html xmlns = "http://www.w3.org/1999/xhtml"> 8 <head> 9 <title>Verifying a username and a password.</title> 10 11 <style type = "text/css"> 12 td { background-color: #DDDDDD } 13 </style> 14 </head> 15 16 <body style = "font-family: arial"> 17 <p style = "font-size: 13pt"> 18 Type in your username and password below. 19 <br /> 20 <span style = "color: #0000FF; font-size: 10pt; 21 font-weight: bold"> 22 Note that password will be sent as plain text 23 </span> 24 </p> 25 2003 Prentice Hall, Inc. All rights reserved.
  • 55. 26 <!-- post form data to password.php --> 55 <form action = "password.php" method = "post"> 27 Outline 28 <br /> 29 Form data is posted to password.php. 30 <table border = "0" cellspacing = "0" password.html 31 style = "height: 90px; width: 123px; (2 of 4) 32 font-size: 10pt" cellpadding = "0"> 33 34 <tr> 35 <td colspan = "3"> 36 <strong>Username:</strong> 37 </td> 38 </tr> 39 40 <tr> 41 <td colspan = "3"> 42 <input size = "40" name = "USERNAME" 43 style = "height: 22px; width: 115px" /> 44 </td> 45 </tr> 46 2003 Prentice Hall, Inc. All rights reserved.
  • 56. 47 <tr> 56 <td colspan = "3"> 48 Outline 49 <strong>Password:</strong> 50 </td> 51 </tr> password.html 52 (3 of 4) 53 <tr> 54 <td colspan = "3"> 55 <input size = "40" name = "PASSWORD" 56 style = "height: 22px; width: 115px" 57 type = "password" /> 58 <br/></td> 59 </tr> 60 61 <tr> 62 <td colspan = "1"> 63 <input type = "submit" name = "Enter" 64 value = "Enter" style = "height: 23px; 65 width: 47px" /> 66 </td> 67 <td colspan = "2"> 68 <input type = "submit" name = "NewUser" 69 value = "New User" 70 style = "height: 23px" /> 71 </td> 2003 Prentice Hall, Inc. All rights reserved.
  • 57. 72 </tr> 57 </table> 73 Outline 74 </form> 75 </body> 76 </html> password.html (4 of 4) 2003 Prentice Hall, Inc. All rights reserved.
  • 58. 58 26.6 Verifying a Username and Password Fig. 26.15 XHTML form for obtaining a username and password. 2003 Prentice Hall, Inc. All rights reserved.
  • 59. 1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 59 2 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> Outline 3 4 <!-- Fig. 26.16: password.php --> 5 <!-- Searching a database for usernames and passwords. --> password.php 6 (1 of 7) 7 <html xmlns = "http://www.w3.org/1999/xhtml"> 8 <head> Variable names, when preceded by the logical 9 <?php negation operator (!), return true if they are empty 10 extract( $_POST ); or set to 0. This checks if a user has submitted a form 11 without specifying a username or password. 12 // check if user has left USERNAME or PASSWORD field blank 13 if ( !$USERNAME || !$PASSWORD ) { Function fieldsBlank is called if the user has 14 fieldsBlank(); Function isset tests whether the notify the user submitted an incomplete form to user has 15 die(); pressed form fields must be completed. that a that all the New User button, indicating 16 } new user must be added. 17 18 // check if the New User button was clicked new To add a user, we open the file 19 if ( isset( $NewUser ) ) { password.txt in append mode and assign the 20 file handle that is returned to variable $file. 21 // open password.txt for writing using append mode 22 if ( !( $file = fopen( "password.txt", 23 "a" ) ) ) { 24 2003 Prentice Hall, Inc. All rights reserved.
  • 60. 25 // print error message and terminate script 60 // execution if file cannot be opened 26 Outline 27 print( "<title>Error</title></head><body> 28 Could not open password file 29 </body></html>" ); password.php 30 die(); Print an error message and terminate script execution (2 of 7) 31 } if the file cannot be opened. 32 33 // write username and password to file and 34 // call function userAdded 35 fputs( $file, "$USERNAME,$PASSWORDn" ); 36 userAdded( $USERNAME ); 37 } 38 else { Function userAdded is called to print a message to the Function fputs writes the name and password to the 39 user to indicate that the username and password were text file.. 40 // if a new user added to the file. is not being added, open file 41 // for reading 42 if ( !( $file = fopen( "password.txt", 43 "r" ) ) ) { 44 print( "<title>Error</title></head> 45 <body>Could not open password file 46 </body></html>" ); 47 die(); 48 } 49 2003 Prentice Hall, Inc. All rights reserved.
  • 61. 50 $userVerified = 0; 61 51 Outline 52 // read each line in file and check username Before entering the while loop, variable 53 // and password Function fgets reads a lineset to 0. text file. $userVerified is from the 54 while ( !feof( $file result !$userVerified variable $line. The ) && is assigned to ) { password.php 55 (3 of 7) 56 // read line from file 57 The while loop executes as long as the there are more $line = fgets( Function chop $file, 255 ); removes the newline character 58 from the and variable $userVerified is lines in the file to read end of the line. Function split still 0 or empty. is called to separate the string at the 59 // remove newline character from end of line specified delimiter (in this case, a comma). The 60 $line = chop( $line ); resulting array usernamein array $fielduser is tested The is stored entered by the . 61 against the one returned in the text file (stored 62 // split username and password in the first element of the array). If they match, 63 $field = split( ",", $line, 2 ); variable $userVerified is set to 1. 64 65 // verify username 66 if ( $USERNAME == $field[ 0 ] ) { 67 $userVerified = 1; 68 69 // call function checkPassword to If function verify checkPassword returns true, function 70 // user’s password accessGranted is called to notify the client that 71 permission if ( checkPassword( $PASSWORD, $field ) has been granted. Otherwise, function 72 == true ) wrongPassword is called. 73 accessGranted( $USERNAME ); 74 else Function checkPassword is called to verify the 75 wrongPassword(); user’s password. Variable $PASSWORD and array $field are passed to the function. 2003 Prentice Hall, Inc. All rights reserved.
  • 62. 76 } 62 } 77 Outline 78 If variable $userVerified has not been set to a 79 // close text file than the while accessDenied is value otherAfter 0, function loop has executed, function 80 fclose( $file ); fclose is called to close has been called to notify the client that access the file. password.php 81 denied. (4 of 7) 82 // call function accessDenied if username has 83 // not been verified Function checkPassword compares the user’s 84 if ( !$userVerified ) password to the password in the file. If they match, 85 accessDenied(); true is returned, whereas false is returned if they 86 } do not. 87 88 // verify user password and return a boolean 89 function checkPassword( $userpassword, $filedata ) 90 { 91 if ( $userpassword == $filedata[ 1 ] ) 92 return true; 93 else 94 return false; 95 } 96 2003 Prentice Hall, Inc. All rights reserved.
  • 63. 97 // print a message indicating the user has been added 63 function userAdded( $name ) 98 Outline 99 { 100 print( "<title>Thank You</title></head> 101 <body style = "font-family: userAdded Function arial; prints a message to the password.php 102 font-size: 1em; client indicating that the user has been added. color: blue"> (5 of 7) 103 <strong>You have been added 104 to the user list, $name. Function accessGranted prints a 105 <br />Enjoy the message to the client indicating that site.</strong>" ); 106 } permission has been granted. 107 108 // print a message indicating permission 109 // has been granted 110 function accessGranted( $name ) 111 { 112 print( "<title>Thank You</title></head> 113 <body style = "font-family: arial; 114 font-size: 1em; color: blue"> 115 <strong>Permission has been 116 granted, $name. <br /> 117 Enjoy the site.</strong>" ); 118 } 119 2003 Prentice Hall, Inc. All rights reserved.
  • 64. 120 // print a message indicating password is invalid 64 function wrongPassword() 121 Outline 122 { Function wrongPassword prints a message to the 123 print( "<title>Access Denied</title></head> client indicating that the password is invalid. 124 <body style = "font-family: arial; password.php 125 font-size: 1em; color: red"> (6 of 7) 126 <strong>You entered an invalid 127 password.<br />Access has 128 been denied.</strong>" ); 129 } 130 131 // print a message indicating access has been denied 132 function accessDenied() 133 { 134 print( "<title>Access Denied</title></head> 135 <body style = "font-family: arial; 136 font-size: 1em; color: red"> 137 <strong> 138 You were denied access to this server. 139 <br /></strong>" ); Function accessDenied prints a message to the 140 } client indicating that access has been denied. 141 2003 Prentice Hall, Inc. All rights reserved.
  • 65. 142 // print a message indicating that fields 65 // have been left blank 143 Function fieldsBlank prints a message to Outline the 144 function fieldsBlank() client indicating that all form fields have not been 145 { completed. 146 print( "<title>Access Denied</title></head> password.php 147 <body style = "font-family: arial; (7 of 7) 148 font-size: 1em; color: red"> 149 <strong> 150 Please fill in all form fields. 151 <br /></strong>" ); 152 } 153 ?> 154 </body> 155 </html> 2003 Prentice Hall, Inc. All rights reserved.
  • 66. 66 26.6 Verifying a Username and Password Fig. 26.16 Verifying a username and password. 2003 Prentice Hall, Inc. All rights reserved.
  • 67. 1 account1,password1 67 2 account2,password2 Outline 3 account3,password3 4 account4,password4 5 account5,password5 password.txt 6 account6,password6 (1 of 1) 7 account7,password7 8 account8,password8 9 account9,password9 10 account10,password10 2003 Prentice Hall, Inc. All rights reserved.
  • 68. 68 26.7 Connecting to a Database • Databases – Store and maintain data – MySQL is a free database product – PHP supports many database operations • Access databases from Web pages 2003 Prentice Hall, Inc. All rights reserved.
  • 69. 1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 69 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 2 Outline 3 4 <!-- Fig. 26.18: data.html --> 5 <!-- Querying a MySQL Database --> data.html 6 (1 of 2) 7 <html xmlns = "http://www.w3.org/1999/xhtml"> 8 <head> 9 <title>Sample Database Query</title> 10 </head> 11 12 <body style = "background-color: #F0E68C"> 13 <h2 style = "font-family: arial color: blue"> 14 Querying a MySQL database. 15 </h2> 16 17 <form method = "post" action = "database.php"> 18 <p>Select a field to display: 19 20 <!-- add a select box containing options --> 21 <!-- for SELECT query --> 2003 Prentice Hall, Inc. All rights reserved.
  • 70. 22 <select name = "select"> 70 <option selected = "selected">*</option> 23 Outline 24 <option>ID</option> 25 <option>Title</option> Select box containing options for a SELECT 26 <option>Category</option> query. data.html 27 <option>ISBN</option> (2 of 2) 28 </select> 29 </p> 30 31 <input type = "submit" value = "Send Query" 32 style = "background-color: blue; 33 color: yellow; font-weight: bold" /> 34 </form> 35 </body> 36 </html> 2003 Prentice Hall, Inc. All rights reserved.
  • 71. 71 26.7 Connecting to a Database Fig. 26.18 Form to query a MySQL database. 2003 Prentice Hall, Inc. All rights reserved.
  • 72. 72 26.7 Connecting to a Database • Interacting with databases – SQL • Structured Query Language • Used to manipulate databases – Several useful functions • mysql_connect • mysql_select_db • mysql_query • mysql_error • mysql_fetch_row • mysql_close 2003 Prentice Hall, Inc. All rights reserved.
  • 73. 1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 73 2 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> Outline 3 4 <!-- Fig. 26.19: database.php --> 5 <!-- Program to query a database and --> database.php 6 <!-- send results to the client. --> (1 of 3) 7 8 <html xmlns = "http://www.w3.org/1999/xhtml"> 9 <head> 10 <title>Search Results</title> 11 </head> 12 13 <body style = "font-family: arial, sans-serif" 14 style = "background-color: #F0E68C"> 15 <?php Build the select query and assign the 16 string to variable $query. 17 extract( $_POST ); Function mysql_connect returns a database 18 handle which represents PHP’s connection to a 19 // build SELECT query database. If this connection is not made, function 20 $query = "SELECT " . $select . " FROM Books"; die is called to terminate script execution. 21 22 // Connect to MySQL 23 if ( !( $database = mysql_connect( "localhost", 24 "httpd", "" ) ) ) 25 die( "Could not connect to database" ); 2003 Prentice Hall, Inc. All rights reserved.
  • 74. 26 74 27 // open Products database Outline 28 if ( !mysql_select_db( "Products", $database )mysql_query Function ) returns an object 29 containing the result set of the query, which die( "Could not open Products database" ); 30 we assign to variable $result. database.php 31 // query Products database (2 of 3) 32 if ( !( $result = mysql_query( $query, $database ) ) ) { Function mysql_select_db is called to specify the 33 print( "Could not execute query! <br />" ); database to be queried. 34 die( mysql_error() ); 35 } 36 ?> 37 38 <h3 style = "color: blue"> 39 Search Results</h3> 40 41 <table border = "1" cellpadding = "3" cellspacing = "2" 42 style = "background-color: #ADD8E6"> 43 44 <?php The for loop iterates through each 45 record in the result set while 46 // fetch each record in result setconstructing an XHTML table from 47 for ( $counter = 0; the results. Variable $counter is 48 $row = mysql_fetch_row( $result incremented by one for each row ); 49 $counter++ ){ retrieved. Function mysql_fetch_row returns an 50 array containing the elements of each row in the result set of our query ($result). 2003 Prentice Hall, Inc. All rights reserved.
  • 75. 51 // build table to display results 75 52 print( "<tr>" ); Outline 53 54 foreach ( $row as $key => $value ) 55 print( "<td>$value</td>" ); database.php 56 (3 of 3) 57 print( "</tr>" ); The foreach loop iterates through the 58 } array containing the elements of each row 59 and prints out each element in an 60 mysql_close( $databaseThe total number of results are printed to the ); individual table cell. 61 ?> client. 62 63 </table> 64 65 <br />Your search yielded <strong> 66 <?php print( "$counter" ) ?> results.<br /><br /></strong> 67 68 <h5>Please email comments to 69 <a href = "mailto:deitel@deitel.com"> 70 Deitel and Associates, Inc. 71 </a> 72 </h5> 73 74 </body> 75 </html> 2003 Prentice Hall, Inc. All rights reserved.
  • 76. 76 26.7 Connecting to a Database Fig. 26.19 Querying a database and displaying the results. 2003 Prentice Hall, Inc. All rights reserved.
  • 77. 77 26.8 Cookies • Cookies – Store information on client computer – Track preferences and other information – Stored as text files on hard drive – Never store sensitive information, such as credit card numbers, in a cookie • Security risk • Cookies and PHP – setcookie function • Name • Value • Expiration date 2003 Prentice Hall, Inc. All rights reserved.
  • 78. 1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 78 2 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> Outline 3 4 <!-- Fig. 26.20: cookies.html --> 5 <!-- Writing a Cookie --> cookies.html 6 (1 of 2) 7 <html xmlns = "http://www.w3.org/1999/xhtml"> 8 <head> 9 <title>Writing a cookie to the client computer</title> 10 </head> 11 12 <body style = "font-family: arial, sans-serif; 13 background-color: #99CCFF"> 14 15 <h2>Click Write Cookie to save your cookie data.</h2> 16 2003 Prentice Hall, Inc. All rights reserved.
  • 79. 17 <form method = "post" action = "cookies.php" 79 style = "font-size: 10pt"> 18 Outline 19 <strong>Name:</strong><br /> Form data is posted to cookies.php. 20 <input type = "text" name = "NAME" /><br /> 21 cookies.html 22 <strong>Height:</strong><br /> (2 of 2) 23 <input type = "text" name = "HEIGHT" /><br /> 24 25 <strong>Favorite Color:</strong><br /> 26 <input type = "text" name = "COLOR" /><br /> 27 28 <input type = "submit" value = "Write Cookie" 29 style = "background-color: #F0E86C; color: navy; 30 font-weight: bold" /></p> 31 </form> 32 </body> 33 </html> 2003 Prentice Hall, Inc. All rights reserved.
  • 80. 80 26.8 Cookies Fig. 26.20 Gathering data to be written as a cookie. 2003 Prentice Hall, Inc. All rights reserved.
  • 81. 1 <?php 81 2 // Fig. 26.21: cookies.php Outline 3 // Program to write a cookie to a client's machine 4 5 extract( $_POST ); cookies.php 6 // write each form field’s value to a cookie and set the (1 of 2) 7 // cookie’s expiration date 8 setcookie( "Name", $NAME, time() + 60 * 60 * 24 * 5 ); 9 setcookie( "Height", $HEIGHT, time() + 60 * 60 * 24 * 5 ); 10 setcookie( "Color", $COLOR, time() + 60 * 60 * 24 * 5 ); 11 ?> Function setcookie takes the name of the 12 cookie to be set as the first argument, 13 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" the value to be stored in the followed by 14 cookie. The optional third argument specifies "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 15 the expiration date of the cookie. 16 <html xmlns = "http://www.w3.org/1999/xhtml"> 17 <head> 18 <title>Cookie Saved</title> 19 </head> 20 21 <body style = "font-family: arial, sans-serif"> 22 <p>The cookie has been set with the following data:</p> 23 2003 Prentice Hall, Inc. All rights reserved.
  • 82. 24 <!-- print each form field’s value --> 82 25 Each <br /><span style = "color: blue">Name:</span> form field’s value is printed to Outline 26 <?php print( $NAME ) ?><br /> confirm the data that has been set as a 27 cookie with the user. 28 <span style = "color: blue">Height:</span> cookies.php 29 <?php print( $HEIGHT ) ?><br /> (2 of 2) 30 31 <span style = "color: blue">Favorite Color:</span> 32 33 <span style = "color: <?php print( "$COLOR">$COLOR" ) ?> 34 </span><br /> 35 <p>Click <a href = "readCookies.php">here</a> 36 to read the saved cookie.</p> 37 </body> 38 </html> Hyperlink to readCookies.php. 2003 Prentice Hall, Inc. All rights reserved.
  • 83. 83 26.8 Cookies Fig. 26.21 Writing a cookie to the client. 2003 Prentice Hall, Inc. All rights reserved.
  • 84. 84 26.8 Cookies • Reading cookies – $_COOKIE environment variable • Array – foreach loop to access each element • Split into key and value 2003 Prentice Hall, Inc. All rights reserved.
  • 85. 85 26.8 Cookies • Cookie storage – Internet Explorer • Stores cookies in Cookies directory • Text file 2003 Prentice Hall, Inc. All rights reserved.
  • 86. 86 26.8 Cookies Fig. 26.22 Cookies directory before a cookie is written. Fig. 26.23 Cookies directory after a cookie is written. 2003 Prentice Hall, Inc. All rights reserved.
  • 87. 1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 87 2 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> Outline 3 4 <!-- Fig. 26.24: readCookies.php --> 5 <!-- Program to read cookies from the client's computer --> readCookies.php 6 (1 of 2) 7 <html xmlns = "http://www.w3.org/1999/xhtml"> 8 <head><title>Read Cookies</title></head> 9 10 <body style = "font-family: arial, sans-serif"> 11 12 <p> 13 <strong> 14 The following data is saved in a cookie on your 15 computer. 16 </strong> 17 </p> 18 2003 Prentice Hall, Inc. All rights reserved.
  • 88. 19 <table border = "5" cellspacing = "0" cellpadding = "10"> 88 <?php 20 The foreach loop iterates through the $_COOKIE PHP creates array $_COOKIE which contains Outline 21 array and prints the name and value of each cookie all cookie values indexed by their names. 22 // iterate through array $_COOKIE and print in an XHTML table. 23 // name and value of each cookie readCookies.php 24 foreach ( $_COOKIE as $key => $value ) (2 of 2) 25 print( "<tr> 26 <td bgcolor="#F0E68C">$key</td> 27 <td bgcolor="#FFA500">$value</td> 28 </tr>" ); 29 ?> 30 31 </table> 32 </body> 33 </html> 2003 Prentice Hall, Inc. All rights reserved.
  • 89. 89 26.8 Cookies Fig. 26.24 Displaying the cookie’s content. 2003 Prentice Hall, Inc. All rights reserved.
  • 90. 90 26.9 Dynamic Content in PHP • Dynamically alter XHTML content – Form’s action property set to same page that contains it – Perform different actions when page is loaded and form is submitted • isset variable – Check for errors • Write different XHTML when errors encountered – $$variable syntax • References variable whose name equals the value of $variable – If input is valid, make MySQL database calls 2003 Prentice Hall, Inc. All rights reserved.