php i basic chapter 3

128
INTRODUCTION TO PHP Server-Side Scripting MySQL PHP Apache Variables Control Structure Looping

Upload: muhamad-al-imran

Post on 22-May-2015

102.030 views

Category:

Technology


5 download

TRANSCRIPT

Page 1: Php i basic chapter 3

INTRODUCTION TO PHP

•Server-Side Scripting•MySQL•PHP•Apache•Variables•Control Structure •Looping

Page 2: Php i basic chapter 3

CLIENT

WEB SERVER

HTTP Request(url)

<HTML><?php PHP code ?></HTML>

Gets Page

<HTML><B>Hello</B></HTML>

Interprets the PHP codeServer response

Browser createsthe web page

Hello

Page 3: Php i basic chapter 3

Server-Side Scripting

A "skrip" adalah koleksi program atau urutan arahan yang ditafsirkan atau dijalankan oleh program lain dan bukannya oleh pemproses komputer. Server-side / Server-side Client-side / Pelanggan-side

Dalam server-side scripting, (seperti PHP, ASP) skrip diproses oleh pelayan Like: Apache, ColdFusion, ISAPI dan Microsoft IIS pada Windows.

Page 4: Php i basic chapter 3

Server-Side Scripting – Continued

Advantages of Server-Side Scripting

Dynamic content. Computational capability. Database and file system access. Network access (from the server only). Built-in libraries and functions. Known platform for execution (as opposed

to client-side, where the platform is uncontrolled.)

Security improvements

Page 5: Php i basic chapter 3

Introduction to PHP

• PHP stands for PHP: Hypertext Preprocessor

• Developed by Rasmus Lerdorf in 1994• It is a powerful server-side scripting

language for creating dynamic and interactive websites.

• It is an open source software, which is widely used and free to download and use (PHP is FREE to download from the official PHP resource: www.php.net).

• It is an efficient alternative to competitors such as Microsoft's ASP.

Page 6: Php i basic chapter 3

Introduction to PHP

• PHP is perfectly suited for Web development and can be embedded directly into the HTML code.

• The PHP syntax is very similar to JavaScript, Perl and C.

• PHP is often used together with Apache (web server) on various operating systems. It also supports ISAPI and can be used with Microsoft's IIS on Windows.

• PHP supports many databases (MySQL, Informix, Oracle, Sybase, Solid, PostgreSQL, Generic ODBC, etc.)

Page 7: Php i basic chapter 3

Introduction to PHP

• What is a PHP File?

• PHP files have a file extension of ".php", ".php3", or ".phtml"

• PHP files can contain text, HTML tags and scripts

• PHP files are returned to the browser as plain HTML 

Page 8: Php i basic chapter 3

Introduction to PHP

What you need to develop PHP Application:

• Install Apache (or IIS) on your own server, install PHP, and MySQL

• OR• Install Wampserver2 (a bundle of PHP,

Apache, and MySql server) on your own server/machine

Page 9: Php i basic chapter 3

PHP Installation Downloads

Free Download PHP: http://www.php.net/downloads.php MySQL Database:

http://www.mysql.com/downloads/index.html Apache Server: http://httpd.apache.org/download.cgi

• How to install and configure apache• Here is a link to a good tutorial from PHP.net on how to install

PHP5: http://www.php.net/manual/en/install.php

Page 10: Php i basic chapter 3

How PHP is Processed

• When a PHP document is requested of a server, the server will send the document first to a PHP processor

• Two modes of operation– Copy mode in which plain HTML is copied

to the output– Interpret mode in which PHP code is

interpreted and the output from that code sent to output

– The client never sees PHP code, only the output produced by the code

Page 11: Php i basic chapter 3

Basic PHP Syntax

• PHP statements are terminated with semicolons ;• Curly braces, { } are used to create compound

statements• Variables cannot be defined in a compound

statement unless it is the body of a function• PHP has typical scripting language characteristics

– Dynamic typing, un-typed variables– Associative arrays– Pattern matching– Extensive libraries

• Primitives, Operations, Expressions– Four scalar types: boolean, integer, double, string– Two compound types: array, object– Two special types: resource and NULL

Page 12: Php i basic chapter 3

Basic PHP Syntax

• A PHP scripting block always starts with <?php and ends with ?> <?php ……………. ?>– Other options are:1. <? ……………… ?> 2. <script> ... </script>

• There are three basic statements to output text with PHP: echo, print, and printf. Example:echo 'This is a <b>test</b>!';

• Comments: – #– //– /* . . . */

Page 13: Php i basic chapter 3

Basic PHP Syntax

Inserting external files: PHP menyediakan empat fungsi yang

membolehkan anda untuk memasukkan kod dari fail luaran : include() or require() include_once() or require_once() functions.

• E.g. include("table2.php");– Included files start in copy mode

Page 14: Php i basic chapter 3

Basic PHP Syntax

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

"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head> <title>Simple PHP Example</title>

<body>

<?phpecho "Hello Class of 2011. This is my first PHP Script";echo "<br />";print "<b><i>What have you learnt and how many friends

have you made?</i></b>";echo "<br /><a href='PHP I-BSIC.ppt'>PHP BASIC</a>";

?></body></html>

Page 15: Php i basic chapter 3

PHP Variables

• Variables are used for storing values, such as numbers, strings or function results, so that they can be used many times in a script.

• All variables in PHP start with a $ sign symbol.

• Variables are assigned using the assignment operator "="

• Variable names are case sensitive in PHP: $name is not the same as $NAME or $Name.

• In PHP a variable does not need to be declared before being set.• PHP is a Loosely Typed

Language.

Example:<html>

<head>

<title>My first PHP page</title>

</head>

<body>

<?php $var1 = 'PHP'; // Assigns a value of 'PHP'

to $var1$var2 = 5; // Assigns a value of 5 to

$var2$var3 = $var2 + 1; // Assigns a value of 6

to $var3

$var2 = $var1; // Assigns a value of 'PHP' to $var2

echo $var1; // Outputs 'PHP‘echo "<br />";echo $var2; // Outputs 'PHP'echo "<br />";echo $var3; // Outputs '6'echo "<br />";echo $var1 . ' rules!'; // Outputs 'PHP

rules!'echo "$var1 rules!"; // Outputs 'PHP

rules!'echo '$var1 rules!'; // Outputs '$var1

rules!‘?>

</body>

</html>

Page 16: Php i basic chapter 3

Variable Naming Rules

A variable name must start with a letter or an underscore "_"

A variable name can only contain alpha-numeric characters and underscores (a-z, A-Z, 0-9, and _ )

If variable name is more than one word, it should be separated with an underscore e.g. ($my_string), or with capitalization ($myString)

Page 17: Php i basic chapter 3

Variable Scope and Lifetime

The scope of a variable defined within a function is  local to that function.

A variable defined in the main body of code has a global scope. 

If a function needs to use a variable that is defined in the main body of the program, it must reference it using the "global" keyword, like this:

• Example:

<?phpfunction mul(){global $start;print "<tr>";for ($num=1; $num <= 10; $num++ ){$cell = $num * $start;print "<td> " . $cell . " </td>";}print "</tr>";}$start = 0;print "<table border=1

cellpadding=3>";while ( $start <=10 ){mul();$start++;}print "</table>";?>

Page 18: Php i basic chapter 3

Strings in PHP

• a string is a sequence of letters, symbols, characters and arithmetic values or combination of all tied together in single or double quotes.

• String literals are enclosed in single or double quotes• Example:

<?php$sum = 20;echo 'the sum is: $sum';echo "<br />";echo "the sum is: $sum";echo "<br />";echo '<input type="text" name="first_name" id="first_name">'; ?>

– Double quoted strings have escape sequences (such as /n or /r) interpreted and variables interpolated (substituted)

– Single quoted strings have neither escape sequence interpretation nor variable interpolation

– A literal $ sign in a double quoted string must be escaped with a backslash, \

– Double-quoted strings can cover multiple lines

Page 19: Php i basic chapter 3

Escaping quotes with in quotes

Example 1:<?php $str = "\"This is a PHP string examples quotes\""; echo $str; ?>

Example 2<?php $str = 'It\'s a nice day today.'; echo $str; ?>

Page 20: Php i basic chapter 3

The Assignment Operator

The Assignment operator is the most widely used and well known of all the operators in PHP. You use it every time you create a variable. The "="(equal to) sign is used, and what it does is it takes the expression from the right and places it into the operand on the left. It is simple.

In this example we use the assignment operator(=) to place a value of 8 into the variable:

<?php $var1 = 8; ?>

We can also combine operators together to produce expression results that are set into our variables as value. We demonstrate this in the next few lessons quite well. Let us continue on.

Page 21: Php i basic chapter 3

Some Types of Operator

Arithmetic Assignment Bitwise Comparison Ternary

• Incrementing/decrementing

• Logical• String

Page 22: Php i basic chapter 3

String Operators

Use a dot to concatenate two strings:e.g.$firstname = ‘Rob’;

$surname = ‘Tuley’;

// displays ‘Rob Tuley’

echo $firstname.’ ‘.$surname;

Page 23: Php i basic chapter 3

Arithmetic Operators

Example Name Result

$a + $b Addition Sum of $a and $b.

$a - $b Subtraction Difference of $a and $b.

$a * $b Multiplication Product of $a and $b.

$a / $b Division Quotient of $a and $b.

$a % $b Modulus Remainder of $a divided by $b.

Page 24: Php i basic chapter 3

Assignment Operators

Example Result

$a = $b Sets $b to the same value as $a.

$a += $b Equivalent to $a = $a + $b.

$a .= $b Equivalent to $a = $a.$b.

Page 25: Php i basic chapter 3

Combining Operators

Note that you can combine operators, for example use =, + and / in one expression:$a = 4;

$b = 2;

$c = $a + $b + ($a/$b);

// $c has value 4+2+(4/2) = 8 Brackets help group operators.

Page 26: Php i basic chapter 3

Comparison Operators

Example Name Result

$a == $b Equal TRUE if $a is equal to $b.

$a != $b Not equal TRUE if $a is not equal to $b.

$a <> $b Not equal TRUE if $a is not equal to $b.

$a < $b Less than TRUE if $a is strictly less than $b.

$a > $b Greater than TRUE if $a is strictly greater than $b.

$a <= $b Less than or equal to TRUE if $a is less than or equal to $b.

$a >= $b Gtr than or equal to TRUE if $a is greater than or equal to $b.

Page 27: Php i basic chapter 3

Comparisons

Comparison expressions return a value of TRUE (or ‘1’) or FALSE (or ‘0’).

e.g.$a = 10;

$b = 13;

// result is true (‘1’)

echo $a < $b;

Page 28: Php i basic chapter 3

Incrementing/Decrementing

Example Name Effect++$a Pre-increment Increments $a by one, then returns $a.

$a++ Post-increment Returns $a, then increments $a by one.

--$a Pre-decrement Decrements $a by one, then returns $a.

$a-- Post-decrement Returns $a, then decrements $a by one.

Page 29: Php i basic chapter 3

Logical Operators

Example Name Result$a and $b And TRUE if both $a and $b are TRUE.

$a or $b Or TRUE if either $a or $b is TRUE.

$a xor $b Xor TRUE if either $a or $b is TRUE, but not both.

!$a Not TRUE if $a is not TRUE.

$a && $b And TRUE if both $a and $b are TRUE.

$a || $b Or TRUE if either $a or $b is TRUE.

Page 30: Php i basic chapter 3

Finally, a tricky one!

A single ? is the ternary operator.

(expr) ? if_expr_true : if_expr_false;

A test expression evaluates to TRUE or FALSE.

TRUE gives first result (before colon) FALSE gives second result (after colon)

Page 31: Php i basic chapter 3

Ternary Operator example

<?php

$a = 10;

$b = 13;

echo $a<$b ? ‘a smaller’:‘b smaller’;

// string ‘a smaller’ is echoed

// to the browser..

?>

Page 32: Php i basic chapter 3

The Concatenation Operator

• The concatenation operator (.)  is used to put two string values together.

• Example:<?php $txt1="Hello Everyone,"; $txt2="1234 is Dan’s home address"; echo $txt1.$txt2;

?>

Page 33: Php i basic chapter 3

Constants in PHP

Constants are named values whose values cannot be changed. When you create a constant you should use all capital letters and underscores separating words to let yourself and others know they are constants. A dollar sign is not needed in front of the name when creating constants. We use the define() function in PHP to create them.

Here is how we create a constant, and use true on the end to make it not worry about letter casing:

Output:The person that created this web page is named Adam Khoury.

<?php

// define(constant_name, value, case_sensitive=true); define("AUTHOR_NAME", "Adam Khoury", true);

echo "The person that created this web page is named " . AUTHOR_NAME . ".";

?>

Page 34: Php i basic chapter 3

Control Structure

Control structures are the building blocks of any programming language. PHP provides all the control structures that you may have encountered anywhere. The syntax is the same as C or Perl.

Making computers think has always been the goal of the computer architect and the programmer. Using control structures computers can make simple decisions and when programmed cleverly they can do some complex things.

Page 35: Php i basic chapter 3

Conditional Statements

1. The If...Else Statement

Syntaxif (condition) code to be

executed if condition is true;

else code to be executed if condition is false;

<?php $d=date("D"); if ($d=="Fri") echo "Have a

nice weekend!"; else echo "Have a nice

day!"; ?>

If more than one line should be executed if a condition is true/false, the lines should be enclosed within curly braces:

<?php $d=date("D"); if ($d=="Fri") { echo "Hello!<br />"; echo "Have a nice

weekend!"; echo "See you on

Monday!"; } ?>

Page 36: Php i basic chapter 3

Conditional Statements

2. The ElseIf Statement

• If you want to execute some code if one of several conditions is true use the elseif statement

Syntaxif (condition) code to be

executed if condition is true;

elseif (condition) code to be executed if condition is true;

else code to be executed if condition is false;

<html><head> <title>good ......</title> </head>

<body><?php $hour = date("H"); if ($hour <= 11) { echo "good morning my

friend"; } elseif ($hour > 11 && $hour <

18) { echo "good afternoon my

friend"; } else { echo "good evening

my friend"; } ?> </body></html>

Page 37: Php i basic chapter 3

PHP Switch Statement

• If you want to select one of many blocks of code to be executed, use the Switch statement.

• The switch statement is used to avoid long blocks of if..elseif..else code.

Syntaxswitch (expression) { case label1: code to be executed

if expression = label1; break; case label2: code to be executed

if expression = label2; break;

default: code to be executed if expression is different from both label1 and label2;

}

switch ($textcolor) { case "black":

echo "I'm black"; break;

case "blue": echo "I'm blue";

break; case "red":

echo "I'm red"; break;

default: // It must be something else echo "too bad!!, I'm something else";

}

Page 38: Php i basic chapter 3

PHP Looping

• Looping statements in PHP are used to execute the same block of code a specified number of times.

• In PHP we have the following looping statements:– while - loops through a block of code if and as

long as a specified condition is true– do...while - loops through a block of code

once, and then repeats the loop as long as a special condition is true

– for - loops through a block of code a specified number of times

– foreach - loops through a block of code for each element in an array

Page 39: Php i basic chapter 3

The while Statement

Syntax

while (condition)

{

// statements

}

Example<html> <head> <title>Let us count

!!!</title></head> <body><?php $limit = 10; echo "<h2> Let us count from 1 to $limit

</h2><br />"; $count = 1; while ($count <= $limit) { echo "counting $count of $limit <br>"; $count++; }?> </body><html>

Page 40: Php i basic chapter 3

The do...while Statement

• The do...while statement will execute a block of code at least once - it then will repeat the loop as long as a condition is true.

Syntax• do { code to be

executed; } while (condition);

Example<html> <body> <?php $i=0; do { $i++; echo "The number is " . $i . "<br />"; } while ($i<5); ?> </body> </html>

Page 41: Php i basic chapter 3

The for Statement

• It is used when you know how many times you want to execute a statement or a list of statements.

Syntax• for (init; cond; incr) { code to be

executed; } Parameters:

• init: Is mostly used to set a counter, but can be any code to be executed once at the beginning of the loop statement.

• cond: Is evaluated at beginning of each loop iteration. If the condition evaluates to TRUE, the loop continues and the code executes. If it evaluates to FALSE, the execution of the loop ends.

• incr: Is mostly used to increment a counter, but can be any code to be executed at the end of each loop.

Example

<html> <body> <?php for ($i=1; $i<=5; $i++) { echo "Hello World!<br />"; } ?> </body> </html>

Page 42: Php i basic chapter 3

The foreach Statement

• The foreach statement is used to loop through arrays.

• For every loop, the value of the current array element is assigned to $value (and the array pointer is moved by one) - so on the next loop, you'll be looking at the next element.

Syntax• foreach (array as value)

{ code to be executed; }

Example<html> <body> <?php $arr=array("one", "two", "three"); foreach ($arr as $value) { echo "Value: " . $value . "<br />"; } ?> </body> </html>

Page 43: Php i basic chapter 3

Object and Classes in PHP

PHP, like most modern programming languages (C++, Java, Perl, JavaScript, etc.), supports the creation of objects.

Creating an object requires you to first define an object class (containing variables and/or function definitions) and then using the “new” keyword to create an instance of the object class. (Note that the object must be defined before you instantiate it.)

<?php

// Assume that the "Person" object has been previously defined. . .

$x = new Person; // creates an instance of the Person class (*no* quotes)

// The object type need not be "hardcoded" into the declaration.

$object_type = 'Person';

$y = new $object_type; // equivalent to $y = new Person;

$z = new Vehicle('Jaguar','green'); // creating an object and passing

// arguments to its constructor

?>

Page 44: Php i basic chapter 3

Defining (declaring) a class

Use the “class” keyword which includes the class name (case-insensitive, but otherwise following the rules for PHP identifiers). Note: The name “stdClass” is reserved for use by the PHP interpreter.

<?php

class Person

{

var $name;

function set_name($new_name) {

$name = $this -> new_name;

}

function get_name() {

return $this -> name;

}

} Use the “$this” variable when accessing properties and functions of the current

object. Inside a method this variable contains a reference to the object on which the method was called.

Page 45: Php i basic chapter 3

Declaring a class (cont.) Properties and functions can be declared as “public” (accessible outside the

object’s scope), “private” (accessible only by methods within the same class), or “protected” (accessible only through the class methods and the class methods of classes inheriting from the class.

Note that unless a property is going to be explicitly declared as public, private, or protected, it need not be declared before being used (like regular PHP variables).

<?phpclass Person

{

protected $name;

protected $age;

function set_name($new_name) {

$name = $this -> new_name;

}

function get_name() {

return $this -> name;

}

}

Page 46: Php i basic chapter 3

Declaring a class (cont.) Classes can also have their own constants defined (using the “const” keyword), can

have their own static properties and functions (using the keyword “static” before “var” or “function”), and can also can constructors and destructors (see below).

Static properties and functions are accessed (see below) using a different format than usual for objects, and static functions cannot access the objects properties (i.e. the variable $this is not defined inside of a static function).

<?php

class HTMLtable {

static function start() {

echo "<table> \n";

}

static function end() {

echo "</table> \n";

}

}

HTMLtable::start();

?>

Page 47: Php i basic chapter 3

Accessing properties and methods

Once you have an object, you access methods and properties (variables) of the object using the -> notation.

<?php

$me = new Person;

$me -> set_name('Russ');

$me -> print_name();

$name = $me -> get_name();

echo $me -> get_name();

$age = 36;

$me -> set_age($age);

?>

Page 48: Php i basic chapter 3

PHP Function

In php a function is a predefined set of commands that are carried out when the function is called.

The real power of PHP comes from its functions.

PHP has more than 700 built-in or predefine functions for you to use. Complete php string reference

You can write your own functions

Page 49: Php i basic chapter 3

Using Built-in Fuctions

• Useful PHP String Functions

Example - strlen() Function

<?php $str = "Hello world!"; echo strlen($str); ?> Example - strlen()

Function<?php $str = “Hello world!”;echo strpos(“$str”,"world"); ?> </body></html>

• Useful PHP String Functions

<?php echo strlen("Hello

world!"); echo "<br />";echo strpos("Hello

world!","world"); ?> </body></html>

Page 50: Php i basic chapter 3

Using Built-in Function

<html> <head> <title>My first PHP page</title> </head> <body><?php $a = abs(-.43);$b = sqrt(16); $c = round(12.3); print "The absolute value of -.43 is " . $a . "<br />"; print "The square root of 16 is " . $b . "<br />"; print "12.3 rounded is " . $c . " and 12.5 rounded is " .

round(12.5); ?> </body></html>

Page 51: Php i basic chapter 3

Using Built-in Function

Examples: Inserting external files: PHP provides four functions that enable you to insert

code from external files: include() or require() include_once() or require_once() functions.

A sample include file called add.php<html> <body>

<?php function add( $x, $y ) { return $x + $y; } ?> <h1>Welcome to my home page</h1> <p>Some text</p>

</body> </html>

Using the include function

<?php include('add.php'); echo add(2, 2); ?>

Page 52: Php i basic chapter 3

Using Built-in Function

Inserting external files - continued: The functions are identical in every way, except how

they handle errors. The include() and include_once() functions generates a

warning (but the script will continue execution) The require() and require_once() functions generates a

fatal error (and the script execution will stop after the error).

These functions are used to create functions, headers, footers, or elements that can be reused on multiple pages. This can save the developer a considerable amount of time

for updating/editing.

Page 53: Php i basic chapter 3

Date Function Formatting

DAYS d - day of the month 2 digits (01-31) j - day of the month (1-31) D - 3 letter day (Mon - Sun) l - full name of day (Monday - Sunday) N - 1=Monday, 2=Tuesday, etc (1-7) S - suffix for date (st, nd, rd) w - 0=Sunday, 1=Monday (0-6) z - day of the year (1=365)

WEEK W - week of the year (1-52)

MONTH F - Full name of month (January - December)m - 2 digit month number (01-12) n - month number (1-12) M - 3 letter month (Jan - Dec) t - Days in the month (28-31)

YEARL - leap year (0 no, 1 yes)o - ISO-8601 year number (Ex. 1979, 2006)Y - four digit year (Ex. 1979, 2006)y - two digit year (Ex. 79, 06)

• Date Function Formatting

• TIMEa - am or pmA - AM or PMB - Swatch Internet time (000 - 999)g - 12 hour (1-12)G - 24 hour c (0-23)h - 2 digit 12 hour (01-12)H - 2 digit 24 hour (00-23)i - 2 digit minutes (00-59)s 0 2 digit seconds (00-59)

• OTHER e - timezone (Ex: GMT, CST)I - daylight savings (1=yes, 0=no)O - offset GMT (Ex: 0200)Z - offset in seconds (-43200 - 43200)r - full RFC 2822 formatted date

Page 54: Php i basic chapter 3

Using Built-in Function

PHP Date() function formatting characters:

Example 1:

<?php$theDate = date("m/d/y");

echo "Today's date is: $theDate";

?>

Example 2

<?php $b = time (); print date("m/d/y",$b) . "<br />"; print date("D, F jS",$b) . "<br />"; print date("l, F jS Y",$b) . "<br />"; print date("g:i A",$b) . "<br />"; print date("r",$b) . "<br />"; print date("g:i:s A D, F jS Y",$b) .

"<br />"; ?>

Page 55: Php i basic chapter 3

Defining and Referencing a Function

Syntaxfunction functionname () { your code }

Example:<html> <body>

<?php Function Name() { echo "Ben John";} Name(); ?> </body> </html>

Page 56: Php i basic chapter 3

PHP Functions - Adding parameters

A parameter is just like a variable.

The parameters are specified inside the parentheses.

Syntax: <?php    function function_name(param_1, ... , param_n)    {       statement_1;       statement_2;       ...      statement_m;

      return return_value;    } ?>

Functions can also be used to return values.

Example:

<html><body>

<?phpfunction add($x,$y) { $total = $x + $y; return $total; }

echo "1 + 16 = " . add(1,16);?>

</body></html>

Page 57: Php i basic chapter 3

PHP Arrays

An array can store one or more values in a single variable name.

There are three different kind of arrays: Numeric array - An array with a numeric

ID key Associative array - An array where each

ID key is associated with a value Multidimensional array - An array

containing one or more arrays

Page 58: Php i basic chapter 3

Numeric Array

• A numeric array stores each element with a numeric ID key.

• There are different ways to create a numeric array:

Example 1• In this example the ID key is

automatically assigned:• $names =

array("Peter","Quagmire","Joe");

Example 2• In this example we assign the ID key

manually:$names[0] = "Peter";$names[1] = "Quagmire"; $names[2] = "Joe";

Example 3:<?php $names[0] = "Peter"; $names[1] = "Quagmire"; $names[2] = "Joe"; echo $names[1] . " and " .

$names[2] . " are ". $names[0] . "'s neighbors"; ?>

Page 59: Php i basic chapter 3

Associative Arrays

• Each ID key is associated with a value.

• When storing data about specific named values, a numerical array is not always the best way to do it.

• There are two ways of creating Associative Array:

Example 1• $ages = array("Peter"=>32,

"Quagmire"=>30, "Joe"=>34);

Example 2• $ages['Peter'] = "32";

$ages['Quagmire'] = "30"; $ages['Joe'] = "34";

Example 3:<?php $ages['Peter'] = "32"; $ages['Quagmire'] = "30"; $ages['Joe'] = "34"; echo "Peter is " .

$ages['Peter'] . " years old.";

?>

Page 60: Php i basic chapter 3

Multidimensional Arrays

• In a multidimensional array, each element in the main array can also be an array. And each element in the sub-array can be an array, and so on.

• Example 1• with automatically

assigned ID keys:

$families = array ( "Griffin"=>array

( "Peter", "Lois", "Megan" ), "Quagmire"=>array

( "Glenn" ), "Brown"=>array

( "Cleveland", "Loretta", "Junior" )

);

Example 2:The array above would look like this if written

to the output:

Array ( [Griffin] => Array

( [0] => Peter [1] => Lois [2] => Megan )

[Quagmire] => Array ( [0] => Glenn )

[Brown] => Array ( [0] => Cleveland [1] => Loretta [2] => Junior ) )

• displaying a single value from the array above:

echo "Is " . $families['Griffin'][2] . " a part of the Griffin family?";

Page 61: Php i basic chapter 3

Strings Function

Strlen Strstr Strpos Substr

Page 62: Php i basic chapter 3

Forms(Getting data from users)

Page 63: Php i basic chapter 3

Forms: how they work

We need to know..

1. How forms work.

2. How to write forms in XHTML.

3. How to access the data in PHP.

Page 64: Php i basic chapter 3

How forms work

Web Server

User

User requests a particular URL

XHTML Page supplied with Form

User fills in form and submits. Another URL is requested and theForm data is sent to this page either inURL or as a separate piece of data.

XHTML Response

Page 65: Php i basic chapter 3

XHTML Form

The form is enclosed in form tags..

<form action=“path/to/submit/page”

method=“get”>

<!–- form contents -->

</form>

Page 66: Php i basic chapter 3

Form tags

action=“…” is the page that the form should submit its data to.

method=“…” is the method by which the form data is submitted. The option are either get or post. If the method is get the data is passed in the url string, if the method is post it is passed as a separate file.

Page 67: Php i basic chapter 3

Form fields: text input

Use a text input within form tags for a single line freeform text input.

<label for=“fn">First Name</label>

<input type="text"

name="firstname"

id=“fn"

size="20"/>

Page 68: Php i basic chapter 3

Form tags

name=“…” is the name of the field. You will use this name in PHP to access the data.

id=“…” is label reference string – this should be the same as that referenced in the <label> tag.

size=“…” is the length of the displayed text box (number of characters).

Page 69: Php i basic chapter 3

Form fields: password input

Use a starred text input for passwords.

<label for=“pw">Password</label>

<input type=“password"

name=“passwd"

id=“pw"

size="20"/>

Page 70: Php i basic chapter 3

Form fields: text input

If you need more than 1 line to enter data, use a textarea.

<label for="desc">Description</label>

<textarea name=“description”

id=“desc“

rows=“10” cols=“30”>

Default text goes here…

</textarea>

Page 71: Php i basic chapter 3

Form fields: text area

name=“…” is the name of the field. You will use this name in PHP to access the data.

id=“…” is label reference string – this should be the same as that referenced in the <label> tag.

rows=“…” cols=“..” is the size of the displayed text box.

Page 72: Php i basic chapter 3

Form fields: drop down

<label for="tn">Where do you live?</label>

<select name="town" id="tn">

<option value="swindon">Swindon</option>

<option value="london”

selected="selected">London</option>

<option value=“bristol">Bristol</option>

</select>

Page 73: Php i basic chapter 3

Form fields: drop down

name=“…” is the name of the field. id=“…” is label reference string. <option value=“…” is the actual data

sent back to PHP if the option is selected.

<option>…</option> is the value displayed to the user.

selected=“selected” this option is selected by default.

Page 74: Php i basic chapter 3

Form fields: radio buttons<input type="radio" name="age"

id="u30“checked=“checked”value="Under30" />

<label for="u30">Under 30</label><br /><input type="radio"

name="age"id="thirty40"value="30to40" />

<label for="thirty40">30 to 40</label>

Page 75: Php i basic chapter 3

Form fields: radio buttons

name=“…” is the name of the field. All radio boxes with the same name are grouped with only one selectable at a time.

id=“…” is label reference string. value=“…” is the actual data sent back

to PHP if the option is selected. checked=“checked” this option is

selected by default.

Page 76: Php i basic chapter 3

Form fields: check boxes

What colours do you like?<br /><input type="checkbox"

name="colour[]"id="r"checked="checked"value="red" />

<label for="r">Red</label><br /><input type="checkbox"

name="colour[]" id="b"

value="blue" /><label for="b">Blue</label>

Page 77: Php i basic chapter 3

Form fields: check boxes

name=“…” is the name of the field. Multiple checkboxes can be selected, so if the button are given the same name, they will overwrite previous values. The exception is if the name is given with square brackets – an array is returned to PHP.

id=“…” is label reference string. value=“…” is the actual data sent back to

PHP if the option is selected. checked=“checked” this option is

selected by default.

Page 78: Php i basic chapter 3

Hidden Fields

<input type="hidden"

name="hidden_value"

value="My Hidden Value" />

name=“…” is the name of the field. value=“…” is the actual data sent back

to PHP.

Page 79: Php i basic chapter 3

Submit button..

A submit button for the form can be created with the code:

<input type="submit"

name="submit"

value="Submit" />

Page 80: Php i basic chapter 3

Fieldset

In XHTML 1.0, all inputs must be grouped within the form into fieldsets. These represent logical divisions through larger forms. For short forms, all inputs are contained in a single fieldset.

<form><fieldset><input … /><input … /></fieldset><fieldset><input … /><input … /></fieldset></form>

Page 81: Php i basic chapter 3

In PHP…

The form variables are available to PHP in the page to which they have been submitted.

The variables are available in two superglobal arrays created by PHP called $_POST and $_GET.

Page 82: Php i basic chapter 3

Access data

Access submitted data in the relevant array for the submission type, using the input name as a key.

<form action=“path/to/submit/page”

method=“get”><input type=“text” name=“email”></form>

$email = $_GET[‘email’];

Page 83: Php i basic chapter 3

A warning..

NEVER TRUST USER INPUT

Always check what has been input. Validation can be undertaken using

Regular expressions or in-built PHP functions.

Page 84: Php i basic chapter 3

A useful tip..

I find that storing the validated data in a different array to the original useful.

I often name this array ‘clean’ or something similarly intuitive.

I then *only* work with the data in $clean, and never refer to $_POST/$_GET again.

Page 85: Php i basic chapter 3

Example

$clean = array();

if (ctype_alnum($_POST['username']))

{

$clean['username'] = $_POST['username'];

}

Page 86: Php i basic chapter 3

Filter example

$clean = array();

if (ctype_alnum($_POST['username']))

{

$clean['username'] = $_POST['username'];

}

$clean = array();

Initialise an array to store filtered data.

Page 87: Php i basic chapter 3

Filter example

$clean = array();

if (ctype_alnum($_POST['username']))

{

$clean['username'] = $_POST['username'];

}

if (ctype_alnum($_POST['username']))

Inspect username to make sure that it is alphanumeric.

Page 88: Php i basic chapter 3

Filter example

$clean = array();

if (ctype_alnum($_POST['username']))

{

$clean['username'] = $_POST['username'];

}

$clean['username'] = $_POST['username'];

If it is, store it in the array.

Page 89: Php i basic chapter 3

Is it submitted?

We also need to check before accessing data to see if the data is submitted, use isset() function.

if (isset($_POST[‘username’])) {

// perform validation

}

Page 90: Php i basic chapter 3

FORM Handling

GET $_GET['name']

POST $_POST['name']

or just use the more general method $_REQUEST[‘name’]

Page 91: Php i basic chapter 3

FORM Example

<form action="test.php" method="post"> <table> <tr> <th>Name:</th> <td><input type="text" name="name"></td> </tr> <tr> <th>Age:</th> <td><input type="text" name="age"></td> </tr> </table></form>

<p>Hello <?=$_POST['name']?>.You are <?=$_POST['age']?> years old.</p>

Page 92: Php i basic chapter 3

Example

(a) A Web page containing a form

(b) A PHP script for handling the output of the form

(c) Output from the PHP script when the inputs are "Barbara" and 24 respectively

Page 93: Php i basic chapter 3
Page 94: Php i basic chapter 3

The need for persistence

Consider these examples Counting the number of “hits” on a website i.e. how many times does a client load your web

page source The questionnaire on computing experience

Somehow your .php needs to remember previous instances of it being requested by a client

Page 95: Php i basic chapter 3

Persistence

Persistence is the ability of data to outlive the execution of the program that created them.

An obvious way of achieving persistence is to simply save the data in a file

Page 96: Php i basic chapter 3

Persistence and HTTPRecall http is a stateless protocol. It remembers nothing about

previous transfers

Two ways to achieve persistence: PHP cookies PHP sessions

HTTPserverClient

CookieSession

Page 97: Php i basic chapter 3

HTTP Cookies

In internet programming, a cookie is a packet of information sent from the

server to client, and then sent back to the server each time it is accessed by the

client.

Introduces state into HTTP (remember: HTTP is stateless)

Cookies are transferred between server and client according to http.

PHP supports http cookies

Cookies can also be thought of as tickets used to identify clients and their

orders

Page 98: Php i basic chapter 3

How Cookies are implemented Cookies are sent from the server to the client via

“Set-Cookie” headers

Set-Cookie: NAME=VALUE; expires=DATE; path=PATH; domain=DOMAIN_NAME; secure

The NAME value is a URL-encoded name that identifies the cookie.

The PATH and DOMAIN specify where the cookie applies

Page 99: Php i basic chapter 3

setcookie(name,value,expire,path,domain,secure)Parameter Description

name (Required). Specifies the name of the cookie

value (Required). Specifies the value of the cookie

expire (Optional). Specifies when the cookie expires.e.g. time()+3600*24*30 will set the cookie to expire in 30 days. If this parameter is not set, the cookie will expire at the end of the session (when the browser closes).

path (Optional). Specifies the server path of the cookie.

If set to "/", the cookie will be available within the entire domain. If set to "/phptest/", the cookie will only be available within the test directory and all sub-directories of phptest.

The default value is the current directory that the cookie is being set in.

domain (Optional). Specifies the domain name of the cookie.To make the cookie available on all subdomains of example.com then you'd set it to ".example.com". Setting it to www.example.com will make the cookie only available in the www subdomain

secure (Optional). Specifies whether or not the cookie should only be transmitted over a secure HTTPS connection. TRUE indicates that the cookie will only be set if a secure connection exists. Default is FALSE.

Page 100: Php i basic chapter 3

Cookies from HTTPCookies from HTTP

GET /*.html HTTP/1.1Host: it026954.domain

GET /*.html HTTP/1.1Host: it026945.domainCookie: name=value

Accept: */*

HTTP/1.1 200 OKContent-type:

text/htmlSet-Cookie: name=value

(content of page)

Client (e.g. Firefox) it026945

Page 101: Php i basic chapter 3

Creating PHP cookiesCreating PHP cookies

Cookies can be set by directly manipulating the HTTP header using

the PHP header() function

<?php header(“Set-Cookie: mycookie=myvalue; path=/; domain=.coggeshall.org”);?>

Page 102: Php i basic chapter 3

Creating cookies with setcookie()Use the PHP setcookie() function:Setcookie (name,value,expire, path, domain, secure)Setcookie (name,value,expire, path, domain, secure)e.g.

<?php setcookie("MyCookie", $value, time()+3600*24); setcookie("AnotherCookie", $value, time()+3600);?>

Name: name of the file Value: data stored in the file Expire: data string defining the life time Path: subset of URLs in a domain where it is valid Domain: domain for which the cookie is valid Secure: set to '1' to transmit in HTTPS

Page 103: Php i basic chapter 3

Reading cookiesReading cookies

<?php

foreach ($_COOKIE as $key=>$val) { print $key . " => " . $val . "<br/>"; }

?>

To access a cookie received from a client, use the PHP

$_COOKIE $_COOKIE superglobal array

Each key in the array represents a cookie - the key name is the cookie name.

Page 104: Php i basic chapter 3

Creating and using Creating and using cookies example cookies example

<?php setcookie("MyCookie", $value, time()+7200); setcookie("AnotherCookie", $value, time()+7);?>

<?php foreach ($_COOKIE as $key=>$val) { print $key . " => " . $val . "<br/>"; }?>

Cookies only become visible on the next page load

Page 105: Php i basic chapter 3

Using headers (wrong approach!)

<!DOCTYPE html PUBLIC "=//W3C//DTD XHMTL 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<html xmlns="http://www.w3.org/1999/xhmtl" xml:lang="en">

<head><title>PHP Script using Cookies</title>

<meta http-equiv="Content-Type" content="text/html; chatset=ISO-8859-1" />

</head>

<body>

<?php

$strValue = "This is my first cookie";

setcookie ("mycookie", $strValue);

echo "Cookie set<br>";

?>

</body>

</html>

Gets an error!:

Warning: Cannot modify header information - headers already sent by (output started at /var/www/html/TESTandre/159339/PHP/cookie_with_headers.php:9) in /var/www/html/TESTandre/159339/PHP/cookie_with_headers.php on line 11

(adapted from Stobart & Parsons (2008))

Page 106: Php i basic chapter 3

Using headersUsing headers

setcookie() did not run before information was sent to the browser...

Cookies have to be sent before the heading elements

Page 107: Php i basic chapter 3

Using headers (correct approach)

<?php

$strValue = "This is my first cookie";

setcookie ("mycookie", $strValue);

echo "Cookie set<br>";

?>

<!DOCTYPE html PUBLIC "=//W3C//DTD XHMTL 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<html xmlns="http://www.w3.org/1999/xhmtl" xml:lang="en">

<head><title>PHP Script using Cookies</title>

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />

</head>

<body>

<?php

echo “<p> A cookie has been set. </p>”;

?>

</body>

</html>

This is the correct approach!

Page 108: Php i basic chapter 3

Deleting a cookie

Set the cookie with its name only:

setcookie(“mycookie”);

Page 109: Php i basic chapter 3

Multiple data items Use explode() e.g.<?php

$strAddress = $_SERVER['REMOTE_ADDR'];

$strBrowser = $_SERVER['HTTP_USER_AGENT'];

$strOperatingSystem = $_ENV['OS'];

$strInfo = "$strAddress::$strBrowser::$strOperatingSystem";

setcookie ("somecookie4",$strInfo, time()+7200);

?>

<?php

$strReadCookie = $_COOKIE["somecookie4"];

$arrListOfStrings = explode ("::", $strReadCookie);

echo "<p>$strInfo</p>";

echo "<p>Your IP address is: $arrListOfStrings[0] </p>";

echo "<p>Client Browser is: $arrListOfStrings[1] </p>";

echo "<p>Your OS is: $arrListOfStrings[2] </p>";

?>

Page 110: Php i basic chapter 3

Where is the cookie stored?

Page 111: Php i basic chapter 3

Where is the cookie stored

Depends on the browser... e.g., firefox/mozilla under /home/a________

Look for cookies.txt in .mozilla directory Usually under:

/home/a______/.mozilla/firefox/asdkfljy.default Cookie is stored only if there is an expiry date Otherwise it is deleted when leaving browser Persistent only if an expiry date is set

Page 112: Php i basic chapter 3
Page 113: Php i basic chapter 3

You can store user information (e.g. username, items selected, etc.) in the server side for later use using PHP session.

SessionsSessions work by creating a unique id (UID) for each visitor and storing variables based on this UID.

The UID is either stored in a cookie or is propagated in the URL.

PHP SessionsPHP Sessions

Page 114: Php i basic chapter 3

When should you use When should you use sessions?sessions? Need for data to stored on the server Unique session information for each user Transient data, only relevant for short time Data does not contain secret information Similar to Cookies, but it is stored on the

server More secure, once established, no data is

sent back and forth between the machines Works even if cookies are disabled Example: we want to count the number of

“hits” on our web page.

Page 115: Php i basic chapter 3

<?php session_start(); ?>

<html><body>

</body></html>

session_start() function must appear BEFORE the <html> tag.

Before you can store user information in your PHP session, you must first start up the session.

Page 116: Php i basic chapter 3

PHP SessionsPHP Sessions Starting a PHP session:

<?php session_start(); ?>

• This tells PHP that a session is requested. • A session ID is then allocated at the server end.

• session ID looks like:sess_f1234781237468123768asjkhfa7891234g

Page 117: Php i basic chapter 3

Session variablesSession variables

$_SESSION e.g., $_SESSION[“intVar”] = 10;

Testing if a session variable has been set:

session_start();

if(!$_SESSION['intVar']) {...} //intVar is set or not

Page 118: Php i basic chapter 3

Registering session variablesRegistering session variables

Instead of setting superglobals, one can register one’s own session variables

<?php$barney = “A big purple dinosaur.”;$myvar_name = “barney”;session_register($myvar_name);

?>

• $barney can now be accessed “globally” from session to session

This only works if the register_globalsregister_globals directive is enabled in php.ini - nowadays this is turned off by default

Use of session_register() is deprecated!

Page 119: Php i basic chapter 3

Make your own session Make your own session variablesvariables

With session_start()session_start() a default session variable is created - the name extracted from the page name

To create your own session variable just add a new key to the $_SESSION$_SESSION superglobal

$_SESSION$_SESSION[‘dug’] = “a talking dog.”;

Use of $_SESSION is preferred, as of PHP 4.1.0.

Page 120: Php i basic chapter 3

Session Example 1

<?php session_start(); if (!isset($_SESSION["intVar"]) ){ $_SESSION["intVar"] = 1; } else { $_SESSION["intVar"]++; } echo "<p>In this session you have accessed this

page " . $_SESSION["intVar"] . "times.</p>"; ?>

Page 121: Php i basic chapter 3

<?php session_start();?><?php$thisPage = $_SERVER['PHP_SELF'];

$pageNameArray = explode('/', $thisPage);$pageName = $pageNameArray[count($pageNameArray) - 1];print "The name of this page is: $pageName<br/>";

$nameItems = explode(‘.', $pageName);$sessionName = $nameItems[0];print "The session name is $sessionName<br/>";

if (!isset($_SESSION[$sessionName])) {$_SESSION[$sessionName] = 0;print "This is the first time you have visited this page<br/>";

} else {

$_SESSION[$sessionName]++;}print "<h1>You have visited this page " . $_SESSION[$sessionName] . " times</h1>";?>

Session Example 2Session Example 2

Page 122: Php i basic chapter 3

Ending sessions

unset($_SESSION[‘name’])–Remove a session variable

session_destroy()– Destroys all data registered to a session– does not unset session global variables and cookies associated with the session–Not normally done - leave to timeout

Page 123: Php i basic chapter 3

Destroying a session completely

<?php// Initialize the session.// If you are using session_name("something"), don't forget it now!session_start();

// Unset all of the session variables.$_SESSION = array();

// If it's desired to kill the session, also delete the session cookie.// Note: This will destroy the session, and not just the session data!if (ini_get("session.use_cookies")) { // Returns the value of the configuration option     $params = session_get_cookie_params();    setcookie(session_name(), '', time() - 42000,        $params["path"], $params["domain"],        $params["secure"], $params["httponly"]    );}

// Finally, destroy the session.session_destroy();?>

http://nz2.php.net/manual/en/function.session-destroy.php

returns the name of the current session

Page 124: Php i basic chapter 3

Session Example 3 <?php

session_start();

if(!isset($_SESSION['strColourBg'])) $_SESSION['strColourBg'] = "red";

else echo "Currently Bg set to " . $_SESSION['strColourBg'] . "<br>";

if(!isset($_SESSION['strColourFg'])) $_SESSION['strColourFg'] = "yellow";

else echo "Currently Fg set to " . $_SESSION['strColourFg'];

if(isset($_POST["submit"]) ) {

$strColourBg = $_POST["strNewBg"];

$strColourFg = $_POST["strNewFg"];

$_SESSION['strColourBg'] = $strColourBg;

$_SESSION['strColourFg'] = $strColourFg;

echo "<br>New Settings";

}

else {

$strColourBg = $_SESSION['strColourBg'];

$strColourFg = $_SESSION['strColourFg'];

echo "<br>Keep old settings";

}

?>

Page 125: Php i basic chapter 3

Session Example 3 (cont.) <head> <style type="text/css">

body {background-color: <?php echo $strColourBg ?>}

p {color: <?php echo $strColourFg?>}

h2 {color: <?php echo $strColourFg?>}

</style></head>

<body>

<h2>h2 colour</h2>

<form action = '<?php echo $SERVER["PHP_SELF"] ?>' method='post'>

<label for="strNewBg"> Background colour: </label>

<select name='strNewBg' id='strNewBg'>

<option>red</option> ... <option>grey</option>

</select>

<label for="strNewFg"> Text colour: </label>

<select name='strNewFg' id='strNewFg'>

<option>yellow</option> ... <option>grey</option>

</select>

<input type='submit' name='submit'/>

</form></body> (adapted from Stobart & Parsons, 2008)

Page 126: Php i basic chapter 3

Examples

php_imagefields.php php_retention.php upload.html upload.php php_imagefields.php php_imagecreation.php php_truetypefonts.php php_file_get_contents.p

hp php_cookie_multipledat

a.php cookie1.php cookie_with_headers.ph

p

session1.php

session2.php

php_session_colours2.php

php_session_destroy.php

Page 127: Php i basic chapter 3

Summary

PHP sessions and cookies are mechanisms for introducing state into HTTP transactions.

Page 128: Php i basic chapter 3

END

Thank You