StudyGuide Week 06

14
Week 06 Investigating PHP This topic provides an overview of PHP (short for PHP: Hypertext Preprocessor). We begin by looking at the history of PHP development, what it was developed for, and the features available in the various versions, particularly PHP 5. PHP is a server-side scripting languages designed to produce dynamic web content. PHP incorporates powerful pattern matching capabilities, arrays, and functions for interacting with a text file. PHP also incorporates database access capabilities. Next, we look the basic syntax of PHP scripts and introduce PHP’s multitype variables. From there you will begin to upload PHP scripts to your public_html directory on infotech where they can be interpreted and executed. Arithmetic operators are covered to allow calculations to be made, and string processing covers PHP’s ereg function, which uses Portable Operating System Interface (POSIX) extended regular expressions to enable pattern matching, data extraction and substitution. Objectives On completion of this topic, you should be able to: 1. Describe the history of PHP 2. Use PHP data types, operators, arrays and control structures 3. Carry out string processing 4. Use regular PHP expressions 5. Use PHP syntax embedded within HTML Text Readings Chapter 9.1 - 9.9, Sebesta, R.W. 2014, Programming the World Wide Web, 8th Ed. Note: This chapter applies to both Topics 5 and 6. Additional Readings There are no additional readings for this topic. PROG2002

Transcript of StudyGuide Week 06

Week 06

Investigating PHP

This topic provides an overview of PHP (short for PHP: Hypertext Preprocessor). We begin by looking at the history of PHP development, what it was developed for, and the features available in the various versions, particularly PHP 5. PHP is a server-side scripting languages designed to produce dynamic web content. PHP incorporates powerful pattern matching capabilities, arrays, and functions for interacting with a text file. PHP also incorporates database access capabilities.

Next, we look the basic syntax of PHP scripts and introduce PHP’s multitype variables. From there you will begin to upload PHP scripts to your public_html directory on infotech where they can be interpreted and executed.

Arithmetic operators are covered to allow calculations to be made, and string processing covers PHP’s ereg function, which uses Portable Operating System Interface (POSIX) extended regular expressions to enable pattern matching, data extraction and substitution.

Objectives

On completion of this topic, you should be able to:

1. Describe the history of PHP

2. Use PHP data types, operators, arrays and control structures

3. Carry out string processing

4. Use regular PHP expressions

5. Use PHP syntax embedded within HTML

Text Readings

Chapter 9.1 - 9.9, Sebesta, R.W. 2014, Programming the World Wide Web, 8th Ed.

Note: This chapter applies to both Topics 5 and 6.

Additional Readings

There are no additional readings for this topic.

PROG2002

CSC10217 Week 06 - Investigating PHP

Page 2

Overview

PHP has become one of the most popular server-side scripting languages used to create dynamic Websites. PHP was created in 1994 by Rasmus Lerdorf to track users on his Website and has been developed over several releases.

In 1995 PHP version 1 was released. It included built-in database support and form capabilities. PHP 2 is no longer a supported version of PHP. PHP version 3 was released in 1997. It included a re-written parser. This led to an explosion in PHP use.

In 2000, PHP version 4 was released. Version 4 featured a re-written core to improve performance of complex applications, and improve the modularity of PHP’s code base. The new core was dubbed the Zend Engine after the creators Zeev Suraski and Andi Gutmans.

PHP is a server-side HTML embedded scripting language. It is an alternative to CGI , Alltaire’s Cold Fusion and Microsoft’s Active Server Pages (ASP).

PHP versions 4 and 5 use a compile-then-execute paradigm. This greatly increases the execution speed of large scripts over PHP version 3, which uses an execute-while parsing paradigm

The text reading covers PHP 5. The SCU server infotech is setup for PHP 5.3.5. The most recent release of PHP is PHP version 5.4.3 (May 2012) which includes support for object-oriented programming.

You will find a wealth of PHP resources at the following Web sites.

Internet: http://www.php.net/manual/en/

http://www.w3schools.com/php/default.asp

PHP Syntax

PHP code is embedded directly into XHTML documents. The PHP code is inserted between the scripting delimiters <?php and ?>. PHP script can also be located in a different file to the HTML. It can be brought into a document using the include construct, with the file name as its parameter. For example:

include(“header.inc”);

This causes the contents of header.inc to be copied into the HTML document where the call appears. The file can contain HTML and/or PHP script.

All variables are preceded with a $ sign and are created the first time they are encountered by the PHP interpreter.

PHP files are saved with the extension .php and stored in your public_html directory. As discussed in previous Topics, you can use an FTP program like FileZilla to upload files to infotech. Telnet can also be used to manipulate the file and directories on infotech.

PROG2002

gcole
Rectangle

CSC10217 Week 06 - Investigating PHP

Page 3

Example - first.php

Our first PHP example demonstrates a variable declaration and simple output.

<!DOCTYPE html>

<!-- Our first PHP script -->

<?php

$name = "John Smith"; // declaration

?>

<html lang="en">

<head>

<meta charset = “utf8”>

<title>A simple PHP document</title>

</head>

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

<p>

<strong>

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

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

</strong>

</p>

</body>

</html>

Internet: http://www.php.net

http://www.w3schools.com/php/default.asp

Activity 6.1 - PHP on infotech

1. Upload each of the example scripts in this topic your public-html directory on infotech using FTP.

2. Run each script uploaded to infotech to verify each one is working.

3. Go to the above Web sites and search for sample scripts covering the information in this Topic. Then upload them to infotech and test each script.

PROG2002

gcole
Rectangle

CSC10217 Week 06 - Investigating PHP

Page 4

PHP Data Types

PHP variables are multi-type. They can contain the following types of data:

Data Type Description

integer whole numbers

double real numbers

string text in single or double quotes

boolean true or false

array data group

object group of associated data and methods

resource external data source

null no value

Table 5.1 PHP Data Types

Data Type Conversions - settype

Data type conversions are used when performing arithmetic operations with variables. The function settype is used to convert one variable type to another. settype takes two arguments, the variable name and the data type it will be converted to

For example: settype ( $teststring, "double");

However, using settype can result in the loss of data. Doubles are truncated when converted to an integer. When a string is converted to a number, the string is truncated to only the number at the beginning of the string. If the string does not begin with a number it will have a null value when converted.

Data Type Conversions - Type Casting

Type casting allows you to create a temporary copy of a variable, and set it to a particular data type. This allows arithmetic operations to be carried out on variables with non-arithmetic data types without the loss of data associated with the settype function.

For example, if $value = "98.6 degrees" then

(double) $value evaluates to 98.6

(integer) $value evaluates to 98

PROG2002

gcole
Rectangle

CSC10217 Week 06 - Investigating PHP

Page 5

Example - data_types.php

The following example, data_types.php, demonstrates the use of type casting and the settype function.

<!DOCTYPE html>

<!-- Demonstration of PHP data types -->

<html lang="en">

<head>

<meta charset=”utf8”>

<title>PHP data types</title>

</head>

<body>

<?php

// declare a string, double and integer

$testString = "3.5 seconds";

$testDouble = 79.2;

$testInteger = 12;

?>

<!-- print each variable’s value -->

<?php print( $testString ) ?> is a string.<br />

<?php print( $testDouble ) ?> is a double.<br />

<?php print( $testInteger ) ?> is an integer.<br />

<br />

Now, converting to other types:<br />

<?php

// call function settype to convert variable

// testString to different data types

print( "$testString" );

settype( $testString, "double" );

print( " as a double is $testString <br />" );

print( "$testString" );

settype( $testString, "integer" );

print( " as an integer is $testString <br />" );

settype( $testString, "string" );

print( "Converting to a string results in $testString <br /><br />" );

$value = "98.6 degrees";

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

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

As a string - " . (string) $value .

"<br />As a double - " . (double) $value .

"<br />As an integer - " . (integer) $value );

?>

</body>

</html>

PROG2002

gcole
Rectangle

CSC10217 Week 06 - Investigating PHP

Page 6

The final print statement in data_types.php also demonstrates the use of the concatenation operator (.) to join multiple strings. String concatenation is discussed in the String Processing section later in this Topic.

Arithmetic Operators

To assign a value to a variable use the = sign. For example:

$a = 5;

$name = "Mary";

To assign a value to a constant use the define statement. For example:

define ("value", 5);

define ("name", "Mary");

As well as the usual operators (+, -, *, /), PHP includes the operators listed in Table 7.2.

Operator Example Equivalent Statement

*= $a*=2; $a=$a*2;

+= $a+=2; $a=$a+2;

-= $a-=2; $a=$a-2;

/= $a/=2; $a=$a/2;

Table 7.2 PHP’s Arithmetic Operators

Example - operators.php

The following example demonstrates the use of arithmetic operators to perform various calculations and tests.

<!DOCTYPE html>

<!-- Demonstration of operators -->

<html lang="en">

<head>

<meta charset=”utf8”>

<title>Using arithmetic operators</title>

</head>

<body>

<?php

$a = 5;

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

// define constant VALUE

define( "VALUE", 5 );

// add constant VALUE to variable $a

PROG2002

gcole
Rectangle

CSC10217 Week 06 - Investigating PHP

Page 7

$a = $a + VALUE;

print("Variable a after adding constant VALUE

is $a <br />");

// multiply variable $a by 2

$a *= 2;

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

// test if variable $a is less than 50

if ( $a < 50 )

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

// add 40 to variable #a

$a += 40;

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

// test if variable $a is 50 or less

if ( $a < 51 )

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

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

elseif ( $a < 101 )

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

inclusive<br />");

else

print("Variable a is now greater than 100

<br />");

// print an uninitialised variable

print("Using a variable before initialising: $nothing <br />");

// add constant VALUE to an uninitialised variable

$test = $num + VALUE;

print("An uninitialised variable plus constant VALUE yields

$test <br />");

// add a string to an integer

$str = "3 dollars";

$a += $str;

print("Adding a string to an integer yields $a <br />");

?>

</body>

</html>

Activity 6.2 - Scalar Variables and Operators

1. Write a php program called variables.php. Assign values to the following variables:

$cash_available = 3800

$item1_cost = 4.50

$item2_cost = 3.10

$item1_order = 45 pairs rubber gloves

$item2_order = 23 scrubbing brushes

PROG2002

gcole
Rectangle

CSC10217 Week 06 - Investigating PHP

Page 8

2. Add code to variables.php to achieve the following:

Print the cost of each order

Print the total cost of both orders

Print the remaining cash available after each order

3. Add code to variables.php to achieve the following:

Convert each item cost to an integer value and recalculate the results from question 2.

Assign all the output results to one string variable using string concatenation and print the variable to the screen.

Arrays

You can use the array function to create a new array and assign values to it. For example:

$fruits = array ("lemon", "orange", "banana", "apple");

Individual array elements can be accessed by, enclosing the index number in square brackets after the array name. For example:

$score [2] = 24;

Array index numbers begin at 0. If a value is assigned to a non-existent array, then an array is created. If a value is assigned to an array and the index number is omitted, then the element is appended to the end of the array

You can use the sort function to order the elements in an array from lowest to highest. For example:

sort $fruits;

Array Control Structures

PHP has functions for iterating through the elements of an array.

Each array has an internal pointer. The function reset sets the pointer to the first element of the array.

The function key returns the index of the element the pointer is referencing.

The function next moves the pointer to the next element.

The foreach loop is a control structure designed for iterating through arrays. The format is:

foreach (<array_name> as <index_value> => <element_value> );

PROG2002

gcole
Rectangle

CSC10217 Week 06 - Investigating PHP

Page 9

Example - arrays.php

The example arrays.php demonstrates array manipulation with indices, foreach loops, for loops and the reset, key and next functions.

Here is some pseudcode that describes the program execution:

Begin

set contents of first array element 0 to "zero"

set contents of first array element 1 to "one"

set contents of first array element 2 to "two"

set contents of first array element 3 to "three"

repeat for all first array elements

display current element

endrepeat

create second array and set contents using array function

repeat for all second array elements

display current element

endrepeat

set contents of third array element "Harvey" to 21

set contents of third array element "Paul" to 18

set contents of third array element "Tim" to 23

repeat for all third array elements

display index name and value of current element

endrepeat

create fourth array using string array function to set string indices

"January" => "first"

"February" => "second"

"December" => "twelfth"

repeat for all fourth array elements

display index name and value of current element

endrepeat

End

The program listing for arrays.php follows.

<!DOCTYPE html>

<!-- Array manipulation -->

<html lang="en">

<head>

<meta charset=”utf8”>

<title>Array manipulation</title>

</head>

PROG2002

gcole
Rectangle

CSC10217 Week 06 - Investigating PHP

Page 10

<body>

<?php

// create array first

print( "<strong>Creating the first array</strong>

<br />" );

$first[ 0 ] = "zero";

$first[ 1 ] = "one";

$first[ 2 ] = "two";

$first[ 3 ] = "three";

// print each element’s index and value

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

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

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

</strong><br />" );

// call function array to create array second

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

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

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

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

</strong><br />" );

// assign values to non-numerical indices

$third[ "Harvey" ] = 21;

$third[ "Paul" ] = 18;

$third[ "Tim" ] = 23;

// iterate through the array elements and print each

// element’s name and value

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

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

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

</strong><br />" );

// call function array to create array fourth using

// string indices

$fourth = array(

"January" => "first", "February" => "second",

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

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

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

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

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

);

PROG2002

gcole
Rectangle

CSC10217 Week 06 - Investigating PHP

Page 11

// print each element’s name and value

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

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

?>

</body>

</html>

String Processing

PHP includes string processing functions allowing you to search strings, make substitutions, extract string data, and concatenate strings. These functions can be used on strings, arrays, text files, and databases.

String Concatenation

To combine multiple strings in the one print statement the concatenation operator (.) can be used.

For example, if $firstname = "John" and $surname = "Smith" then:

print ("Thank you ".$firstname." ".$surname);

evaluates to:

Thank you John Smith

As shown in data_types.php above, strings can also be concatenated with values displayed by casts to other types such as integer and double.

String Comparison

To compare two strings, use the function strcmp.

If the first string alphabetically precedes the second string, the value -1 is returned

If the strings are equal, the value 0 is returned

If the first string alphabetically follows the second string, the value 1 is returned

Example - compare.php

The following example, compare.php, demonstrates string comparison using strcmp and the relational operators <, > and ==.

<!DOCTYPE html> <!-- String Comparison -->

<html lang="en">

<head>

<meta charset=”utf8”> <title>String Comparison</title> </head> <body> <?php // create array fruits $fruits = array( "apple", "orange", "banana" );

PROG2002

gcole
Rectangle

CSC10217 Week 06 - Investigating PHP

Page 12

// iterate through each array element for ( $i = 0; $i < count( $fruits ); $i++ ) { // call function strcmp to compare the array element // to string "banana" if ( strcmp( $fruits[ $i ], "banana" ) < 0 ) print( $fruits[ $i ]." is less than banana " ); elseif ( strcmp( $fruits[ $i ], "banana" ) > 0 ) print( $fruits[ $i ]. " is greater than banana " ); else print( $fruits[ $i ]." is equal to banana " ); // use relational operators to compare each element // to string "apple" if ( $fruits[ $i ] < "apple" ) print( "and less than apple! <br />" ); elseif ( $fruits[ $i ] > "apple" ) print( "and greater than apple! <br />" ); elseif ( $fruits[ $i ] == "apple" ) print( "and equal to apple! <br />" ); } ?> </body> </html>

Regular Expressions

More powerful string comparisons can be achieved by using the ereg function (depreciated in PHP 5.3), or the preg_match (Perform a regular expression). preg_match expressions contain the pattern to search for and the string to search. preg_match uses PERL compatible regular expressions.

Metacharacter can be added to the search pattern:

placing a caret (^) symbol before the pattern, searches for the pattern at the beginning of the string

placing a dollar sign ($) at the end of the pattern, searches for the pattern at the end of the string

placing a full stop (.) in a search pattern will match any single character placing an i at the end of the pattern ignores case (upper/lower) Square brackets in a search pattern will match any character listed within the brackets.

Ranges can be created by using a dash (-). For example [A-Z], matches any character between A and Z (capital).

The asterisk (*) is used to indicate the preceding pattern may occur 0 to many times. For example [A-Z]*

To store the results of a search: Place a third argument in the expression (an array to hold result of search) Place the search pattern you want to store in parentheses - (“/ /”) use the i to ignore

case - (“/ /i”) The match is placed in the position 0 of the array variable (third argument).

preg_replace can be used to replace a pattern in a string (see following code)

PROG2002

gcole
Rectangle

CSC10217 Week 06 - Investigating PHP

Page 13

Example - expression.php

Our next example, expression.php, demonstrates the use of ereg and the related functions eregi and ereg_replace. Program execution is described in the code comments. preg match (useing eregi and ereg_replace are described in detail in the PHP manual (there is a copy on the infotech server).

<!DOCTYPE html> <!—- Regular Expression -->

<html lang="en">

<head>

<meta charset=”utf8”> <title>Using Regular expressions</title> </head>

<body>

<?php

$search = "Now is the time";

print( "Test string is: '$search'<br /><br />" );

// call function ereg to search for pattern 'Now'

// in variable search

if ( preg_match( "/Now/", $search ) )

print( "String 'Now' was found.<br />" );

// search for pattern 'Now' in the beginning of

// the string

if (preg_match ( "/^Now/", $search ) )

print( "String 'Now' found at beginning

of the line.<br />" );

// search for pattern 'Now' at the end of the string

if (preg_match ( "/Now$/", $search ) )

print( "String 'Now' was found at the end of the line.<br />" );

// search for any word ending in 'ow'

if (preg_match ( "/[a-z]*ow]/i", $search, $match ) )

print( "Word found ending in 'ow': " .

$match[0] . "<br />" );

// search for any words beginning with 't'

print( "Words beginning with 't' found: ");

while (preg_match( "/t[a-z]*/i", $search, $match )){

print( $match[0] . " " ); // remove the first occurrence of a word beginning // with 't' to find other instances in the string $search = preg_replace( “/”.$match[ 0 ].”/”, "", $search ); } print( "<br />" ); ?>

PROG2002

gcole
Rectangle

CSC10217 Week 06 - Investigating PHP

Page 14

</body> </html>

Activity 6.3 - Arrays and String Comparisons

1. Write a PHP program called states.php that creates a scalar variables called $states with the value "New South Wales, Victoria, Tasmania, South Australia, Western Australia, Northern Territory, Queensland"

Search for a state ending in "and". Store the name of the state in element 0 of an array named $statesarray.

Search for a state beginning with "n" and ending with "y". Use a case insensitive comparison, and store the name of the state in element 1 of $statesarray.

Search for states ending with "a" and store the name of each state in subsequent elements of the array.

Print the array to the screen

2. Take the states.php script and modify it to:

Find and print out all states with the word "Australia" in their title

Display the states in alphabetic order

3. Write a PHP script called order.php that creates a scalar variable with the value "Mason Training: 25 rolls of tape @ $1.20 each, 16 metal rulers @ $1.50 each, and 30 containers of pepper @ $0.98 each"

Extract the details of the order; calculate each line item and the total of the order.

Print the results to the screen.

4. Do Exercises 9.1, 9.3 and 9.5 on Page 48 of the text

Summary

This Topic familiarised you with the basic syntax of PHP and the general capabilities of the language. In the next topic, we will begin by looking at how to view client/server environment variables, to allow us to provide client specific information. Following this we examine form processing and business logic.

PROG2002

gcole
Rectangle