Chapter: Internet & World Wide Web HOW TO PROGRAM - Rich Internet Application Server Technologies - PHP

Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail

PHP Basics

The power of the web resides not only in serving content to users, but also in responding to requests from users and generating web pages with dynamic content.

PHP Basics

The power of the web resides not only in serving content to users, but also in responding to requests from users and generating web pages with dynamic content. Interactivity be-tween the user and the server has become a crucial part of web functionality, making PHP—a language written specifically for interacting with the web—a valuable tool.

Installing PHP

PHP code is embedded directly into XHTML documents, though these script segments are interpreted by the server before being delivered to the client. This allows the document author to write XHTML in a clear, concise manner. PHP script file names end with .php.

To run a PHP script, PHP must first be installed on your system. All examples and exercises in this chapter have been verified using PHP 5.2.3, the most current release at the time of publication. The most recent version of PHP can be downloaded from, and installation instructions are available at  manual/en/installation.php. Be sure to check for specific instructions that pertain to

the server you want to use. During setup, when the Choose Items to Install window is dis-played, expand the Extensions menu by clicking the small plus sign to its left. Then click the down arrow to the left of the MySQL option, and select the Will be installed on local hard drive option. This will ensure that your PHP script will be able to access your MySQL database server for examples later in this chapter.

Although PHP can be used from the command line, a web server is necessary to take full advantage of the scripting language. Before continuing, files from the Chapter 23 examples directory to the web server’s root directory (e.g., C:\Inetpub\wwwroot for IIS or C:\Program Files\Apache Software Foundation\Apache2\htdocs for Apache on Win-

dows or /var/www/html or similar on Linux).

Simple PHP Program

Figure 23.1 presents a simple PHP program that displays a welcome message. In PHP, code is inserted between the scripting delimiters <?php and ?>. PHP code can be placed anywhere in XHTML markup, as long as the code is enclosed in these delimiters. Line 1 uses function print to output the XML declaration. This avoids the <? in the XML dec-

1    <?php print( '<?xml version = "1.0" encoding = "utf-8"?>' ) ?>


2    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"


3          "">


5    <!-- Fig. 23.1: first.php -->


6    <!-- Simple PHP program. -->


7    <html xmlns = "">


8    <?php


9          $name = "Harvey"; // declaration and initialization


10   ?><!-- end PHP script -->


11         <head>


12               <title>Using PHP document</title>


13         </head>


<body style = "font-size: 2em">

15                <p>


16                      <strong>

17            <!-- print variable name’s value -->


18                            Welcome to PHP, <?php print( "$name" ); ?>!


19                      </strong>

20                </p>


21         </body>




Fig. 23.1 | Simple PHP program

laration getting interpreted as an incorrect PHP scripting delimiter. Line 9 declares vari-able $name and assigns it the string “Harvey”. All variables are preceded by a $ and are created the first time they are encountered by the PHP interpreter. PHP statements ter-minate with a semicolon (;).

Line 9 also contains a single-line comment, which begins with two forward slashes (//). Text to the right of the slashes is ignored by the interpreter. Single-line comments can also begin with the pound sign (#). Multiline comments begin with delimiter /* and end with delimiter */.


Line 18 outputs the value of variable $name by calling function print. The actual value of $name is printed, not the string "$name". When a variable is encountered inside a double-quoted ("") string, PHP interpolates the variable. In other words, PHP inserts the variable’s value where the variable name appears in the string. Thus, variable $name is replaced by Harvey for printing purposes. All operations of this type execute on the server before the XHTML document is sent to the client. You can see by viewing the source of a PHP document that the code sent to the client does not contain any PHP code.

PHP variables are loosely typed—they can contain different types of data (e.g., inte-gers, doubles or strings) at different times. Figure 23.2 introduces these data types.


Converting Between Data Types

Converting between different data types may be necessary when performing arithmetic operations with variables. Type conversions can be performed using function settype. Figure 23.3 demonstrates type conversion of some types introduced in Fig. 23.2.


1    <?php print( '<?xml version = "1.0" encoding = "utf-8"?>' ) ?>


2    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"


3          "">


5    <!-- Fig. 23.3: data.php -->


6    <!-- Data type conversion. -->


7    <html xmlns = "">


8          <head>


9                 <title>Data type conversion</title>


10         </head>


11         <body>


12               <?php


13                      // declare a string, double and integer


14                      $testString = "3.5 seconds";


15                      $testDouble = 79.2;


16                      $testInteger = 12;


17               ?><!-- end PHP script -->


19               <!-- print each variable’s value and type -->


20               <?php


21                      print( "$testString is a(n) " . gettype( $testString )

22    . "<br />" );

print( "$testDouble is a(n) " . gettype( $testDouble )

24                            . "<br />" );


25                      print( "$testInteger is a(n) " . gettype( $testInteger)

26                            . "<br />" );


27                ?><!-- end PHP script -->


28                <br />


29                converting to other data types:<br />


30                <?php


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" );


print( "converting back to a string results in

$testString <br /><br />" );

43                      // use type casting to cast variables to a different type


44                      $data = "98.6 degrees";


45                      print( "before casting, $data is a " .

46                            gettype( $data ) . "<br /><br />" );


47                      print( "using type casting instead: <br />

48            as a double: " . (double) $data .


49                            "<br />as an integer: " . (integer) $data );


50                      print( "<br /><br />after casting, $data is a " .


51                          gettype( $data ) );


52                ?><!-- end PHP script -->


53         </body>



Fig. 23.3 | Data type conversion.


Lines 14–16 of Fig. 23.3 assign a string to variable $testString, a floating-point number to variable $testDouble and an integer to variable $testInteger. Variables are automatically converted to the type of the value they are assigned. For example, variable $testString becomes a string when assigned the value "3.5 seconds". Lines 22–27 print the value of each variable and their types using function gettype, which returns the current type of its argument. Note that when a variable is in a print statement but not part of a string, enclosing the variable name in double quotes is unnecessary. Lines 35, 38 and 40 call settype to modify the type of each variable. Function settype takes two argu-ments—the variable whose type is to be changed and the variable’s new type.


Calling function settype can result in loss of data. For example, doubles are truncated when they are converted to integers. When converting from a string to a number, PHP uses the value of the number that appears at the beginning of the string. If no number appears at the beginning, the string evaluates to 0. In line 35, the string "3.5 seconds" is converted to a double, storing 3.5 in variable $testString. In line 38, double 3.5 is converted to integer 3. When we convert this variable to a string (line 40), the variable’s value becomes "3"—much of the original content from the variable’s declaration in line 14 is lost.


Another option for conversion between types is casting (or type casting). Unlike settype, casting does not change a variable’s content—it creates a temporary copy of a variable’s value in memory. Lines 48–49 cast variable $data’s value (declared in line 17) from a string to a double and an integer. Casting is useful when a different type is required in a specific operation but you would like to retain the variable’s original value and type. Lines 45–51 show that the type and value of $data remain unchanged even after it has been cast several times.


The concatenation operator (.) combines multiple strings in the same print state-ment, as demonstrated in lines 45–51. A print statement may be split over multiple lines—all data that is enclosed in the parentheses and terminated by a semicolon is printed to the XHTML document.



Arithmetic Operators

PHP provides several arithmetic operators, which we demonstrate in Fig. 23.4. Line 13 declares variable $a and assigns to it the value 5. Line 17 calls function define to create a named constant. Function define takes two arguments—the name and value of the con-stant. An optional third argument accepts a bool value that specifies whether the constant is case insensitive—constants are case sensitive by default.

Line 20 adds constant VALUE to variable $a. Line 25 uses the multiplication assign-ment operator *= to yield an expression equivalent to $a = $a * 2 (thus assigning $a the value 20). Arithmetic assignment operators—like the ones described in Chapter 7—are syntactical shortcuts. Line 33 adds 40 to the value of variable $a.


1     <?php print( '<?xml version = "1.0" encoding = "utf-8"?>' ) ?>


2     <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"


3           "">


5     <!-- Fig. 23.4: operators.php -->


6     <!-- Using arithmetic operators. -->


7     <html xmlns = "">


8           <head>


9                  <title>Using arithmetic operators</title>


10          </head>


11          <body>


12                 <?php

13                       $a = 5;


14                       print( "The value of variable a is $a <br />" );


16                       // define constant VALUE


17                       define( "VALUE", 5 );


19                       // add constant VALUE to variable $a

20                       $a = $a + VALUE;


print( "Variable a after adding constant VALUE

22        is $a <br />" );


24                       // multiply variable $a by 2

25                       $a *= 2;


26                       print( "Multiplying variable a by 2 yields $a <br />" );


28                       // test if variable $a is less than 50

if ( $a < 50 )


30        print( "Variable a is less than 50 <br />" );


32        // add 40 to variable $a

33        $a += 40;


34        print( "Variable a after adding 40 is $a <br />" );


36        // test if variable $a is 50 or less

37        if ( $a < 51 )



38        print( "Variable a is still 50 or less<br />" );


40        // test if variable $a is between 50 and 100, inclusive


41        elseif ( $a < 101 )



42        print( "Variable a is now between 50 and 100,

43                    inclusive<br />" );

44        else    

45        print( "Variable a is now greater than 100 <br />" );


47        // print an uninitialized variable


48        print( "Using a variable before initializing:



49        $nothing <br />" ); // nothing evaluates to ""


51        // add constant VALUE to an uninitialized variable


52        $test = $num + VALUE; // num evaluates to 0


53        print( "An uninitialized variable plus constant

54        VALUE yields $test <br />" );


56                      // add a string to an integer


57                      $str = "3 dollars";


58                      $a += $str;


59                      print( "Adding a string to variable a yields $a <br />" );


60                ?><!-- end PHP script -->


61         </body>



Fig. 23.4 | Using arithmetic operators.


Uninitialized variables have the value undef, which evaluates to different values, depending on its context. For example, when undef is used in a numeric context (e.g., $num in line 52), it evaluates to 0. In contrast, when undef is interpreted in a string context (e.g., $nothing in line 49), it evaluates to an empty string ("").


Strings are automatically converted to integers or doubles when they are used in arith-metic operations. In line 58, a copy of the value of variable str, "3 dollars", is converted to the integer 3 for use in the calculation. The type and value of variable $str are left unchanged.


Keywords (examples from Fig. 23.4 include if, elseif and else) may not be used as identifiers. Figure 23.5 lists all keywords.


Initializing and Manipulating Arrays


PHP provides the capability to store data in arrays. Arrays are divided into elements that behave as individual variables. Array names, like other variables, begin with the $ symbol. Figure 23.6 demonstrates initializing and manipulating arrays. Individual array elements are accessed by following the array’s variable name with an index enclosed in square brack-ets ([]). If a value is assigned to an array that does not exist, then the array is created (line


PHP keywords






































































15). Likewise, assigning a value to an element where the index is omitted appends a new element to the end of the array (line 18). The for statement (lines 21–22) prints each element’s value. Function count returns the total number of elements in the array. In this example, the for statement terminates when the counter ($i) is equal to the number of array elements.


Line 28 demonstrates a second method of initializing arrays. Function array creates an array that contains the arguments passed to it. The first item in the argument list is stored as the first array element (recall that the first element’s index is 0), the second item is stored as the second array element and so on. Lines 30–31 display the array’s contents.


1     <?php print( '<?xml version = "1.0" encoding = "utf-8"?>' ) ?>


2     <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"


3           "">


5     <!-- Fig. 23.6: arrays.php -->


6     <!-- Array manipulation. -->


7     <html xmlns = "">


8           <head>


9                  <title>Array manipulation</title>


10          </head>


11          <body>



13                       // create array first


14                       print( "<strong>Creating the first array</strong><br />" );

15                       $first[ 0 ] = "zero";

16                       $first[ 1 ] = "one";

17                       $first[ 2 ] = "two";


18                       $first[] = "three";


20                       // print each element’s index and value

for ( $i = 0; $i < count( $first ); $i++ )

22        print( "Element $i is $first[$i] <br />" );


24        print( "<br /><strong>Creating the second array

25        </strong><br />" );


27        // call function array to create array second


28        $second = array( "zero", "one", "two", "three" );




30        for ( $i = 0; $i < count( $second ); $i++ )

31        print( "Element $i is $second[$i] <br />" );


33        print( "<br /><strong>Creating the third array

34        </strong><br />" );


36        // assign values to entries using nonnumeric indices


37        $third[ "Amy" ] = 21;


38        $third[ "Bob" ] = 18;


39        $third[ "Carol" ] = 23;


41        // iterate through the array elements and print each


42        // element’s name and value


43        for ( reset( $third ); $element = key( $third ); next( $third ) )



44        print( "$element is $third[$element] <br />" );


46        print( "<br /><strong>Creating the fourth array

47        </strong><br />" );


49        // call function array to create array fourth using


50        // string indices


51        $fourth = array(


            "January"      => "first"                                            

52                                            ,           "February" => "second",    

53        "March"          => "third",       "April" => "fourth",   

54        "May"  => "fifth",        "June"            => "sixth",     

55        "July"  => "seventh", "August"       => "eighth",  

56        "September"  => "ninth",     "October"       => "tenth",    

57        "November"   => "eleventh","December" => "twelfth"   

58        );                                                         


60        // print each element’s name and value


61        foreach ( $fourth as $element => $value )

62        print( "$element is the $value month <br />" );


63        ?><!-- end PHP script -->


64        </body>


65        </html>


Fig. 23.6 | Array manipulation.


In addition to integer indices, arrays can have float or nonnumeric indices (lines 37– 39). An array with noninteger indices is called an associative array. For example, indices Amy, Bob and Carol are assigned the values 21, 18 and 23, respectively.


PHP provides functions for iterating through the elements of an array (line 43). Each array has a built-in internal pointer, which points to the array element currently being ref-erenced. Function reset sets the internal pointer to the first array element. Function key returns the index of the element currently referenced by the internal pointer, and function next moves the internal pointer to the next element and returns the element. In our script, the for statement continues to execute as long as function key returns an index. Function next returns false when there are no more elements in the array. When this occurs, func-tion key cannot return an index, $element is set to false and the for statement termi-nates. Line 44 prints the index and value of each element.


The array $fourth is also associative. To override the automatic numeric indexing performed by function array, you can use operator =>, as demonstrated in lines 51–58. The value to the left of the operator is the array index and the value to the right is the ele-ment’s value.

The foreach control statement (lines 61–62) is specifically designed for iterating through arrays, especially associative arrays, because it does not assume that the array has consecutive integer indices that start at 0. The foreach statement starts with the array to iterate through, followed by the keyword as, followed by two variables—the first is assigned the index of the element, and the second is assigned the value of that index. (If there is only one variable listed after as, it is assigned the value of the array element.) We use the foreach statement to print the index and value of each element in array $fourth.


Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail

Copyright © 2018-2020; All Rights Reserved. Developed by Therithal info, Chennai.