Php Web-based applications: main elements HTTP PROTOCOL CLIENT - - PowerPoint PPT Presentation

php web based applications main elements
SMART_READER_LITE
LIVE PREVIEW

Php Web-based applications: main elements HTTP PROTOCOL CLIENT - - PowerPoint PPT Presentation

Php Web-based applications: main elements HTTP PROTOCOL CLIENT SIDE SERVER SIDE HTTP request An HTTP request consists of: a request method (verb) , resource URL , header fields ( metadata ), body ( data ) HTTP 1.1 defines 9 request


slide-1
SLIDE 1

Php

slide-2
SLIDE 2

Web-based applications: main elements

HTTP PROTOCOL CLIENT SIDE SERVER SIDE

slide-3
SLIDE 3

HTTP request

  • An HTTP request consists of: a request method (verb), resource URL,

header fields (metadata), body (data)

  • HTTP 1.1 defines 9 request methods, among which:
  • GET: Retrieves the resource identified by the request URL
  • HEAD: Returns the headers identified by the request URL

POST: Sends data of unlimited length to the Web server

  • POST: Sends data of unlimited length to the Web server
  • PUT: Stores a resource under the request URL
  • DELETE: Removes the resource identified by the request URL
  • HTTP 1.0 includes only the GET, HEAD, and POST methods.
slide-4
SLIDE 4

HTTP response

  • An HTTP response contains a result code, header fields, and a body.
  • Some commonly used status codes include:
  • 100: Continue
  • 200: OK
  • 401: the request requires HTTP authentication
  • 404: the requested resource is not available
  • 404: the requested resource is not available
  • 500: an error occurred inside the HTTP server that prevented it from
  • fulfilling the request
  • 503: the HTTP server is temporarily overloaded and unable to handle the

request

  • For detailed information on this protocol, see the Internet RFCs: HTTP/1.0

(RFC 1945), HTTP/1.1 (RFC 2616). (http://www.rfc-editor.org/rfc.html)

slide-5
SLIDE 5

Example

slide-6
SLIDE 6

Example

slide-7
SLIDE 7

HTTP is ‘stateless’

  • Although HTTP uses the TCP protocol, it has no notion of end-

user

  • For example, filling in data through multi-page forms requires

the server to keep track of which client is requesting the page.

First Name: Second Name: …. Location:

  • --:

….

First step Second step

slide-8
SLIDE 8

Static web pages

HTTP PROTOCOL

  • Content is pre-determined
  • Web pages are static

HTTP PROTOCOL Content

slide-9
SLIDE 9

Sequence diagram

BROWSER HTTPD Get URL

FILE

Get html file

FILE SYSTEM

Send html file Render html

slide-10
SLIDE 10

Dynamic web pages

  • Content of a page is not static
  • Page content is changes based on:

– User input, form completion,etc. Database interaction – Database interaction – External data sources (db, service provider)

  • Server side techniques
  • Client side techniques
slide-11
SLIDE 11

Technique overview

  • Server side

– CGI (Common Gateway Interface)

  • An http request triggers the execution of an independent program
  • Data passed via standard input or environment variables

– Script

code executed inside the server process

  • code executed inside the server process
  • Interleaved with html code (php)
  • Confined into a different page (code behind, e.g., ASP.NET)
  • Client Side

– Script

  • Source code passed from the server and executed by the browser

– Compiled code

  • Applet (no longer used…)
slide-12
SLIDE 12
  • BROWSER

HTTPD Get URL Send html file CGI-process Execute program Build html on-the-fly

FILE SYSTEM

Read/Write data Client sends the request along with data (e.g., from a form) The server lunches a process and transmits data input to the program The program writes a html page The web server sends the page back to the client Send html file Render html Build html on-the-fly

SYSTEM

slide-13
SLIDE 13
  • BROWSER

HTTPD Get URL Send html file CGI-process Execute program Build html on-the-fly Query DB Send html file Render html Build html on-the-fly

slide-14
SLIDE 14
  • HTTPD

CGI PROCESS CGI

FILE SYSTEM

slide-15
SLIDE 15
  • round-trip time

HTTPD CGI PROCESS CGI

FILE SYSTEM

One process per request

slide-16
SLIDE 16
  • round-trip time

HTTPD + functions..

FILE SYSTEM

Integrate the functionality as an additional module of the server process… (script)

slide-17
SLIDE 17
  • Make the browser ‘smart’

(execute code or script) HTTPD + functions..

FILE SYSTEM

Integrate the functionality as an additional module of the server process… (script)

slide-18
SLIDE 18
  • WEB SERVER

SCRIPT

html document

SCRIPT

Script engine WEB Client HTTP

  • Pages are generated by a program
  • A html document at the server side includes the code to be

executed (script)

  • The code is delimited via special escape characters
  • The web server extracts the script part from the document
  • A script engine runs the code
  • Web server replaces the script with the output of the

execution

  • Client sees pure html (no way to access the code)

Script engine

slide-19
SLIDE 19

Principle of Active Server Page

  • Code behind
  • 2 files

– Standard html file + custom web control Code behind file (handler code for events) – Code behind file (handler code for events)

  • We see later on
slide-20
SLIDE 20
  • Web Client

Script engine

  • html document at the client side contains the code to be

executed

  • The code is delimited via special escape characters
  • The client extracts the script part from the document
  • Executes the code
  • It can perform computation, remote communication, change

the rendering of a document

  • It can access local events (mouse events,..)

Script engine

slide-21
SLIDE 21

Client-side vs server-side

  • Client-side

– Minimal processing on the server. Server sends web page with embedded script. Client browser executes the script executes the script – Client browser may not fully support, or script execution turned off – Security issue (user can see the script)

slide-22
SLIDE 22

Client-side vs server-side

  • Server-side

– Easier to create large-scale site. Create a small set

  • f dynamic pages

– Poor coding programmer may open resources to – Poor coding programmer may open resources to attack through security flaws

slide-23
SLIDE 23

Introduction to PHP

  • Scripting language
  • Server side execution

Code is scattered inside a html document – Code is scattered inside a html document – The web server executes the code and produces a simple html page.

slide-24
SLIDE 24

PHP code embedding

  • !"#$!%

& & !"#$!' &

  • !

" # ! short_open_tags INI option;

slide-25
SLIDE 25

PHP code embedding

  • !"#$!%

&

  • !"#$!%

"#$

  • &

!"#$!' &

  • $%!

%&" # ! short_open_tags INI option;

  • 1.1.php
slide-26
SLIDE 26

Variables

  • A variable always starts with the dollar sign $

– $a – $A – $1 (not allowed)

  • Identifiers are case sensitive (not when referring to function)

Variable and function can have the same name!

  • Variable and function can have the same name!
slide-27
SLIDE 27

Types

  • Basic types like in other programming languages

– Boolean, Integer, Floating Point, Object,

  • Main difference concerns:

– string (regular expression,…)

  • single quoted (variables are not replaced with their values)

double quoted (variables are replaced with their values)

  • double quoted (variables are replaced with their values)
  • here-doc

– array (associative arrays)

  • Other types:

– null

  • No type associated yet

– resource

  • Generic type, e.g. the result of a query
slide-28
SLIDE 28

Types

  • PHP uses a Weakly Typed System
  • variables’ type is not declared
  • PHP automatically converts the variable to the correct data

type, depending on how they are set

  • $integer=10

$integer=10

  • $float = 10.0
  • $string = “10”
slide-29
SLIDE 29

Some example

  • !"#"

$$ %& '

slide-30
SLIDE 30

echo statement

  • Placing a variable outside quotes outputs the variable’s value

(line 2)

  • Single quote ' sends literal string output (line 3), no variable

value substitution

  • Double quote “ sends variable value (line 4)
  • Double quote “ sends variable value (line 4)

<?php $a=6; echo $a; echo 'The var name is $a'; echo "The var contains $a"; ?> Note: no declaration (line 1) 1 2 3 4 1.2.php

slide-31
SLIDE 31

echo statement

  • To achieve newlines in browser, use appropriate

tagging

  • Use \ to escape (negate) the effect of the following

character character

<?php $a=6; echo $a; echo 'The var name is $a'. '<br>'; echo "The var contains $a"; ?> <?php echo "She said, \"How are you?\""; echo "<a href=\"page.htm\">link</a>"; ?> 1.3.php 1.4.php

slide-32
SLIDE 32

print_r()

  • print_r() can be used to "dump" variable
  • utput, typically for debugging of complex

structures.

<?php echo "<pre>"; print_r($_SERVER); echo "</pre>"; ?>

slide-33
SLIDE 33

Comments

  • Multi-line comments

/* This is a multi-line comment */

  • Single line comments

// This single line is commented // This single line is commented # So is this single line

– PHP comments are distinct from HTML comments in that PHP comments are not sent to the client browser.

slide-34
SLIDE 34

Constant

  • Unchangeable values. In all caps by convention. No $.

<?php define('MYCONST',100); define('NAME',"My Name");

  • To output, must list constant name outside of ' and ".
  • echo "Hello, ".NAME;
  • Predefined system constants also exist.
  • To see a complete list:

print_r(get_defined_constants())

define('NAME',"My Name"); ?>

slide-35
SLIDE 35

Variable’s scope

  • Names inside a function has local scope
  • Script level names can be accessed through the special built-

in array $GLOBALS

$m

main script

$a is only visible in the function Af’s scope $m can be seen via GLOBALS[‘m’] $a $m

function Af function Bf main script

$b $b is only visible in the function Bf’s scope $a is not visible $m can be seen via GLOBALS[‘m’]

slide-36
SLIDE 36

Predefined System "Superglobals"

  • Provide access to key runtime data elements.
  • Set by and managed through web server run-

time environment and available to the script. Superglobals are key to form processing,

  • Superglobals are key to form processing,

cookies, and other techniques.

slide-37
SLIDE 37

Some Superglobals

  • $_GET[ ]. An array that includes all the GET variables that PHP

received from the client browser.

  • $_POST[ ]. An array that includes all the POST variables that

PHP received from the client browser.

  • $_COOKIE[ ]. An array that includes all the cookies that PHP

received from the client browser.

  • $_SERVER[ ]. An array with the values of the web-server

variables.

slide-38
SLIDE 38

Example

  • What’s this code doing?

<?php echo '<pre>'; print_r($GLOBALS); print_r($GLOBALS); echo '</pre>'; ?>

slide-39
SLIDE 39

Managing variables

  • isset ()

– determines whether a certain variable has already been declared by PHP.

  • unset()

– “undeclares” a previously set variable, and frees any memory that was used by it if no other variable references its value.

  • empty ()

– empty() may be used to check if a variable has not been declared or its value is false.

slide-40
SLIDE 40

Example

<?php $user = (isset($_GET[‘user’]))? $_GET[‘user’]: ‘’; … ?>

slide-41
SLIDE 41

Operators

  • +, -, *, /, %, ++, -- same as other languages
  • Combining above with = for assignment can be

done:

  • +=, -=, *=, /=, %=, .=

+=, -=, *=, /=, %=, .=

  • Two Comparison operators
  • == (performs type conversion)
  • === (no type conversion)
  • ‘1’==1 true
  • ‘1’===1 false
slide-42
SLIDE 42

Variable variables

<?php $name = "John"; $$name = "Registered user"; print $John; //display “Registered user” ?> ?> John $name Registered user $$name (=$John)

slide-43
SLIDE 43

Conditional control structures

( ( (

  • )

( ) (

  • )
  • (

) (

  • <?php if ($num < 0): ?>

<h1>$num is negative</h1> <?php elseif($num == 0): ?> <h1>$num is zero</h1> <?php else: ?> <h1>$num is positive</h1> <?php endif; ?> if ($num<0) print '<h1>$num is negative</h1>'; elseif ($num==0) print '<h1>$num is zero</h1>'; else print '<h1>$num is positive</h1>';

slide-44
SLIDE 44

Traditional loop control structures

#% ( #% ) ( #%

  • #%

& & " " * !* !+* !* !+* !* !+ ( ( for ($i = 0; $i <= count($array); $i++) { } $count = count($array); for ($i = 0; $i <= $count; $i++) { }

slide-45
SLIDE 45

'

  • '
  • (

  • )
  • *#
  • #)
  • #

– +,

slide-46
SLIDE 46

, " --(-*-."-(-/0,/ , " --(-*-."-(-/1(,/,/ 1() , " -*-(-(-/,/ 2() , " -*-(-(-/,/,/

  • , " -"(-(-3"(-."--/,/

4%.&) , " -%&*-(-.%-."-5&-/,/ 4%.) , " -%&*-(-.%-."-6-/,/

slide-47
SLIDE 47

'#

,((- "-- % -$--/

# . (%( % )% %(7(89(59*(9.%5&93"( %

slide-48
SLIDE 48

#

, --/

  • #

,/#!,/ ,/#!:,/ ,/ ,/ ,/ ,/ ,/ ,/#:!,/ ,/#:!:,/

slide-49
SLIDE 49

Exercise

  • Write a simple php program that displays the

Pitagora’s table. The size of the table is a parameter passed through a form..

slide-50
SLIDE 50

Processing data form

html FORM Collects information PHP Script Send data PHP Script (form processing) DB access Send .html back html output

  • f results
slide-51
SLIDE 51

Creating a form

  • Key elements:

– Input fields must be contained inside a form tag. – All input fields must have a name. – Names cannot have spaces in them. Fields should be – Names cannot have spaces in them. Fields should be named well for clear identification.

  • Form action should be URL to PHP processing

script.

  • Appropriate form transmission method selected:

– GET or POST.

slide-52
SLIDE 52

GET vs POST

  • Name/value pairs appended in clear text to the URL of

the receiving page/script.

  • Each name/value pair separated by '&'. Value data

automatically URL encoded.

  • Names are taken from the form field names.

Names are taken from the form field names.

  • GET URLs can be saved, bookmarked, etc. and used to

recall the script with the same data.

  • GET strings provide 'transparency' that may/may not

be desired.

  • Long GET strings may be problematic.
  • Data available into the $_GET superglobal
slide-53
SLIDE 53

GET vs POST

  • Data is encoded in the page request body sent by the

browser, but not shown in the URL. Unseen to user.

  • Since data not part of URL, bookmarking and reusing

URL to recall the script with the same data is not URL to recall the script with the same data is not possible.

  • Large POST packets not a problem.
  • On most browsers, hitting 'refresh' causes post data

to be retransmitted.

  • Data available into the $_POST superglobal
slide-54
SLIDE 54

)

,%(/ ,%/,/;,/,%/ ,/ ,%/;,%/ $(!!(! )! ,/ ,/ ,/<=(),/,/*+(,-,(,,,/,/ ,/ ,/<=(),/,/*+(,-,(,,,/,/ ,/ ,/1(),/,/, " >*>(>$(>/,/ ,/ ,/ ,/2(),/,/, " >*>(>$(>/,/,/ ,/ ,/?#),/,/*+(, $,(, $, ,/,/ ,/ , >:>/*+(, *.,(, ,/*(,0 ,,/,/ ,/

  • ,/

,%(/

slide-55
SLIDE 55

)

,%(/ ,%/,/;,/,%/ ,/ ,%/;,%/ $(!!(! )! ,/ ,/ ,/<=(),/,/*+(,-,(,,,/,/

  • ,/

,/<=(),/,/*+(,-,(,,,/,/ ,/ ,/1(),/,/, " >*>(>$(>/,/ ,/ ,/ ,/2(),/,/, " >*>(>$(>/,/,/ ,/ ,/?#),/,/*+(, $,(, $, ,/,/ ,/ , >:>/*+(, *.,(, ,/*(,0 ,,/,/ ,/

  • ,/

,%(/

slide-56
SLIDE 56

http://localhost/register.php?email=PSD&first_name=Piattaforme&last_name=SW&password=Pippo&register=Register

key value

slide-57
SLIDE 57

Input validation

  • Never assume a form:

– is filled out completely – Contains the type of information requested – Has been submitted by a benign user Has been submitted by a benign user – Only contains the fields and values or value ranges expected

  • Check all form data to verify that it is

complete and valid …

  • … and secure!
slide-58
SLIDE 58

Input validation

  • Required Fields are filled
  • Type is correct
  • Length is ‘reasonable’
  • Structure adhere to a scheme
  • Structure adhere to a scheme

– Regular expression – Check consistency

  • No malicious data

– SQL injection – Cross-site scripting

slide-59
SLIDE 59

Helpful form validation functions

  • Functions exist for testing data types:
  • is_numeric($x), etc.,.
  • isset($var)

does $var exist? – does $var exist?

  • empty($var)

– returns false unless $var contains an empty string, 0, "0", NULL, or FALSE.

slide-60
SLIDE 60

Example

  • How to check if first name is

correct?

$fn= $_GET[‘first_name’]; if (empty($fn]) || !isnumeric($fn) || strlen ($fn)<3 || strlen ($fn)>10) die(“Not valid data…”);

slide-61
SLIDE 61

Other tricky checks

  • Radio buttons and check box may not be set

$ if !(isset($_GET[‘gender'])) && ($_GET[‘gender’]==‘Male’ || $_GET[‘gender’]==‘Famale’)): die(“…”)

  • Even if the number of options are known, check the actual

value is a best practice… why?

slide-62
SLIDE 62

Other tricky checks

  • Suppose you are designing a guest book, or a

survey where people tell their impression

'<script language='Javascript'>alert('ALLARM!');</script>'

slide-63
SLIDE 63

User authentication: naïve approach

<h1>Login</h1> <form method=“get" action="login.php"> <table> <tr> <td>User name:</td> <td> <input type='text' name=‘user'/></td> </tr> <tr> <td>Password:</td> <td> <input type='password' name=‘pwd'/></td> </tr> ..

<?php $query=“SELECT login_id FROM users WHERE users=‘$user’ AND pwd=‘$pwd’ ”; $ans = mysql_query($query) .. ?>

.. </table> </form>

http://example.com/login?user=pippo&pwd=pippo

slide-64
SLIDE 64

SQL injection

  • Exploiting an application that takes data from user input and

uses it to form an SQL query without proper "sanitation".

  • Let consider this…

# starts a comment

http://example.com/login?user=admin’;# $query=“SELECT login_id FROM users WHERE users=‘$user’ AND pwd=‘$pwd’ ”; $query=“SELECT login_id FROM users WHERE users=‘admin’; # AND pwd=‘’ ”;

# starts a comment

slide-65
SLIDE 65

Preventing

  • Every time you give user chance to enter data, you MUST

check to be sure not trying to manipulate your application. Create and use a clean() function like this

function clean($input, $maxlength) { $input = trim($input) $input = substr($input,0,$maxlength); $input = substr($input,0,$maxlength); $input = escapeShellCmd($input); $input = htmlspecialchars($input,ENT_QUOTES); return $input; }

  • escapeshellcmd() escapes characters that might be used to trick a shell

command into executing arbitrary commands.

  • htmlspecialchars() prevents user-supplied text from containing HTML markup.
slide-66
SLIDE 66

Self referencing Sticky form

  • Form display and form processing can be

consolidated into one script.

  • Requiring a user to retype all form data in event
  • f error/omission reduces usability.
  • Allows "sticky form": display error message to
  • Allows "sticky form": display error message to

user and also retain values the user has already entered.

  • Design (at minimum):

– Form validity checking embedded on page with form. – Form submits to itself for processing. Typically done using PHP superglobal $_SERVER[PHP_SELF].

slide-67
SLIDE 67

Sticky form pseudo-code

  • If form submitted:

– Check validity – If not valid display the form back again with field set set

  • Send the form
slide-68
SLIDE 68

Gluing script

Script1 Script2 Check ok Script2 Check nok

slide-69
SLIDE 69

Array

  • The key is optional, and when it’s not specified, the key is

automatically assigned one more than the largest previous integer key (starting with 0).

array([key =>] value, [key =>] value, ...)

  • 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

slide-70
SLIDE 70

Examples

1. array(1, 2, 3) 2. array(0 => 1, 1 => 2, 2 => 3) 3. array ("name" => "John", "age" => 28) 4. array(1 => "ONE", "TWO", "THREE") 5. array(1 => "ONE", 2 =>"TWO", 3 => "THREE") 6. array (array ("name" => "John", "age" => 28), array ("name" => "Barbara", "age" => 67)) "Barbara", "age" => 67)) 1 and 2 are same, 3 and 5 are same, 6 is a nested array

slide-71
SLIDE 71

Examples

!:! :@A :@A: :@:A 8

  • @A/

@A/: @:A/

  • print_r($arr1)
  • (-/-B%-!--/

:C :@-(-A-B%- :@--A:C :D >:%(> E :%(

slide-72
SLIDE 72

Traversing

  • $key contains the currently iterated value’s key
  • & if present allows to modify the array
  • $value contains the value

foreach($array as [$key =>] [&] $value)

  • B%-!-5-!-5-!-F-
  • G% ),/-

% &/."D

  • H&.",/-

E

The players are: #0 = John #1 = Barbara #2 = Bill #3 = Nancy

slide-73
SLIDE 73

Exercise

  • Format the output of the players as a html

table

slide-74
SLIDE 74

Exercise

,7 %

  • B%-!-5-!-5-!-F-

>G% ,/,--/> % &/." D ,$,)!12+!),$$,)!1/*!),$, ,$,)!12+!),$$,)!1/*!),$, E >,/> 7/

concat double quoted to replace $key with its value

slide-75
SLIDE 75

list, each

  • B%-!-5-!-5-!-F-

#%&!.% D

  • H&.-

E

each() returns the current key/value pair as an array with four elements: the elements 0, "key", 1 and "value" list() assigning multiple array elements to multiple variables in one statement

slide-76
SLIDE 76

LAB

  • LAB1.

– Scrivere uno script che costruisca la tabella di Pitagora n x n

  • LAB2. Sticky form

– Scrivere uno script che genera un form per l’inserimento di nome e cognome. Se i due campi non sono completi rigenera una form con i valori nei campi rimempiti una form con i valori nei campi rimempiti

  • LAB 3.

– Scrivere una generica funzione di “sanity check”, che a partire da un vettore ‘signature’ contentente tipo, caratteristica dei campi della form (required o meno) e nome funzione:

  • controlli se tutti i campi di una form sono stati riempiti
  • Converta I tipi come specificato
  • Applichi una funzione a tutti gli argomenti
slide-77
SLIDE 77

Functions

  • Any valid PHP code may appear inside a user-

defined function, even other function…

  • Functions need not be defined before they are

referenced referenced

  • Call-by-reference, call-by-value, default value,

variable-length argument, lambda-style function

slide-78
SLIDE 78

Parameter passing

function function_name (arg1, arg2, arg3, …) { statement list } function square($n) { $n = $n*$n; } function square(&$n) { $n = $n*$n; } parameter by-value … by-reference

slide-79
SLIDE 79

Default value

function makeAcoffee ($type=“espresso”) { return “Making a cup of $type”; } echo makeAcoffee(); echo MakeAcoffee(“French”)

  • The default value must be a constant
  • Default arguments should be on the right side of any non-default

argument

echo MakeAcoffee(“French”)

slide-80
SLIDE 80

Variable-length argument list

function foo() { $numargs = func_num_args(); echo "Number of arguments: $numargs\n"; } foo(1, 2, 3); foo(1, 2, 3);

slide-81
SLIDE 81

Variable function

  • If a variable name has parentheses appended to

it, PHP looks for a function with that name and executes it

function foo() {echo “in foo()<br>”;} function foo() {echo “in foo()<br>”;} Function bar($arg = ‘’) { echo “in bar(); argument was $arg”<br>”; } $func = ‘foo’; $func(); #call foo() $fun = ‘bar’; $func(‘test’);

slide-82
SLIDE 82

Static variables

function do_something() { static $first_time = true; if ($first_time) { // Execute this code only the first time the function is called ... ... $first_time=false; } // Execute the function's main logic every time the function is called ... }

slide-83
SLIDE 83

Array_map

  • Applies a callback function to the elements of

the given arrays

<?php function Double($a){return 2*$a;}; function Double($a){return 2*$a;}; $in = range(1,5); $out = array_map("Double",$in); print_r($out); ?>

  • Other interesting functions (see manual):
  • array_walk
  • array_reduce
slide-84
SLIDE 84

Closure

  • Closure allows to define an anonymous

function

<?php $out = array_map(function ($a){return 2*$a;},$in); $out = array_map(function ($a){return 2*$a;},$in); ?> <?php $double =function ($a){return 2*$a;}; $out = array_map($double,$in); ?>

slide-85
SLIDE 85

Exercise: generic sanity check function

  • Design a function that parametrically checks

– if all required fields are set – Type convert values

slide-86
SLIDE 86

Code inclusion control structures

*$ *$3 4* I") . " " 4* 4*3 I") .

include $_SERVER["DOCUMENT_ROOT"] . "/myscript.php"; include "http://www.example.org/example.php";

slide-87
SLIDE 87

Eval

  • Include/require actually “execute” the

included script

  • Eval, allows to dynamically execute php string

code code

slide-88
SLIDE 88

Persistency

  • Cookie, Session

– Per browser data storage, no cross-browser data exchange

  • File, DB

File, DB

– Site level persistence storage

slide-89
SLIDE 89
  • +#,
  • ##
  • +)-./0#,
  • #
  • +,
  • +,
slide-90
SLIDE 90
  • +#,
  • ##
  • +)-./0#,
  • #
  • +,
  • +,

562% 0(77687'

  • (*"9:5+5;<9;<<%<<%<<='

('$()$ )*9) 62% 0(77687

http header sent from the server to the client Header sent from the client to the server

slide-91
SLIDE 91

Inspecting http header

  • Browsers can install plug-in to inspect http

headers

  • For example, liveHTTPHeader for firefox
slide-92
SLIDE 92

,7 % .3 >?' 7/

Output must be buffered

7/ ,%(/ ,%/,/6&*( ,/,%/ ,/ ,7 % 2>+62",,? 7/ ,/ ,%(/

set a cookie (see documentation)

slide-93
SLIDE 93

Cookie in PHP

  • Cookie can be accesed via superglobal

variable, $_COOKIE

<?php print_r($_COOKIE); ?>

slide-94
SLIDE 94

Example

  • Implement a simple counter using Cookie
slide-95
SLIDE 95

Solution

<?php

  • b_start();

?> <HTML> <HEAD> <TITLE>COUNTER</TITLE> </HEAD> <BODY> <form method=“post" action="counter.php"> <table> <tr><td colspan='2'> <input type='submit' value='Inc' name='inc'/> </td></tr> <tr><td colspan='2'> <input type='submit' value='Dec'name='dec'/></td></tr> </table> </form>

slide-96
SLIDE 96

Solution

<?php if (!isset($_COOKIE[C])): print "Counter=0"; setcookie(C,0); else: $Counter = $_COOKIE[C]; if (isset($_POST[inc])): $Counter++; endif; if (isset($_POST[inc])): $Counter++; endif; if (isset($_POST[dec])): $Counter--; endif; print "Counter=$Counter"; setcookie(C,$Counter); endif; ?> </BODY> </HTML>

slide-97
SLIDE 97

Tic Tac Toe

Player arrives Player enters Display Form P=P1, enters for the first time P=P1, returns, P2 not entered display “Wait” Set Cookie P1 display “Wait” Index SYNC arrives P=P2 P=P1, returns, P2 entered P = Player P1 = First Player that arrives P2 = Second Player redirect Set Cookie P2 redirect Display Form

slide-98
SLIDE 98

Tic Tac Toe

PLAY move Display new view PLAY Update the view Check winner

slide-99
SLIDE 99

Session

  • A PHP session allows for storing information locally

at the server on a per session basis

– Session data path is specified in the session.save_path of php.ini Data session can be stored in a database – Data session can be stored in a database

  • PHP generates a session ID and sends it out as a

cookie with name PHPSESSIONID

  • The client sends the session ID each time it interacts

again with the same site

slide-100
SLIDE 100

Example

<?php session_start(); ?> create the id and an empty _SESSION array, stored at the server side cookie cookie’s content

slide-101
SLIDE 101

Access to a private area

  • Session can be used to protect a page
  • When trying to access a page, check if

authorization is set… If not, redirect to a login page and then back

  • If not, redirect to a login page and then back

to the page…

  • ..otherwise just continue..
slide-102
SLIDE 102

Example

<?php

  • b_start();

session_start(); ?> <?php if (!(isset($_SESSION['auth'])&&($_SESSION['auth']=='ok’))) { $url = $_SERVER['PHP_SELF']; header("location: login.php?url=$url"); } auth not set get this url.. redirect to login } ?> <?php //check login… $_SESSION['auth']='ok'; $url=$_GET['url']; header(“location: $url"); ?> Included in example.php login.php set auth get original url redirect back http://localhost/example.php http://localhost/login?url=example.php http://localhost/example.php

slide-103
SLIDE 103

Example: shopping cart

  • Simple example
  • User can login…
  • User can select/deselect items…

…then check out…

  • …then check out…
slide-104
SLIDE 104

" )"

cookie ‘uid’ not set success / set cookie ‘uid’

12

login failure

" "

click on logout unset cookie ‘uid’

passwd DB

want to register done

slide-105
SLIDE 105

31 4315

  • 1!6
  • 78
  • #9
  • :1
slide-106
SLIDE 106

Open/create a db

+;<!;<!=;>??, @31##)" ,7 % 43-340?2<J5-!!9 ,7 % #@. -340?2<J5-!9 43-340?2<J5-!!9

  • J5K?<F<J--L-
  • 7/

340?2<J5 #@. -340?2<J5-!9

  • %J5K?<F<J-
  • 7/
slide-107
SLIDE 107

Create a table

$I" - 600A6> $+2+" $ " 4*+ Sql statment

A:)

Executes a result-less query against a given database bool queryExec ( string $query [, string &$error_msg ] )

  • I"

4*+ ?

  • =/4*+->134*+?'

db

PRODUCTS

A:) +,

slide-108
SLIDE 108

Insert a row

I"-7B07B0A6>$"$ "4*+?CA>9",C,"9?- =/I"<*I"

  • J

I"

  • JMJ
  • db

PRODUCTS

slide-109
SLIDE 109

Update/delete

$db->queryexec('DELETE FROM PRODUCTS WHERE id=2'); $db->queryexec('UPDATE PRODUCTS SET id=19 WHERE id=4');

slide-110
SLIDE 110

Fetch results

query fetch, fetch all, 3N2;" seek rewind, current… unbufferedquery 3N2O" forward only, much faster

slide-111
SLIDE 111

Fetch results

$q = "SELECT * FROM PRODUCTS;"; $qr = $db->query($q); //Executes a query against a given database and returns a result handle $r = $qr->fetchAll();//Fetches all rows from a result set as an array of arrays foreach ($r as $entry) { echo $entry['id'].' '.$entry['description'].' '.$entry['quantity'].'<br>'; } 1 DVD 1

slide-112
SLIDE 112

LAB /Project (shopping cart 2)

  • PRODUCT table

– View content – Insert items – Delete items – Delete items

  • Password DB

– User registration – User authentication

slide-113
SLIDE 113

Login Form

  • http://www.html-form-guide.com/php-

form/php-registration-form.html

slide-114
SLIDE 114

OO Model

  • An OO program is a collection of objects
  • Every object is an instance of a class
  • An object has properties

An object has a set of methods

  • An object has a set of methods
slide-115
SLIDE 115

Constructor

  • Unified constructor name
  • __construct()

class MyClass { function __construct() { function __construct() { echo "Inside constructor"; } }

slide-116
SLIDE 116

Destructor

  • __destruct()
  • Called when an object is

destroyed (no more reference)

class MyClass { function __destruct() { print "An object of type MyClass is being destroyed\n"; } } $obj = new MyClass(); $obj = NULL; An object of type MyClass is being destroyed

slide-117
SLIDE 117

Copying objects

class MyClass { public $var = 1; }

  • bj1
  • bject

$obj1 = new MyClass(); $obj2 = $obj1;

  • bj2

$obj2 = $obj1; $obj2->var = 2; print $obj1->var; //print 2 $obj1 = new MyClass(); $obj2 = clone $obj1; $obj2->var = 2; print $obj1->var; //print 1

  • bj1
  • bject
  • bj2
  • bject
slide-118
SLIDE 118

Access protection of member variables

class MyDbConnectionClass { public $queryResult; protected $dbHostname = "localhost"; private $connectionHandle; // ... } class MyFooDotComDbConnectionClass extends MyDbConnectionClass { protected $dbHostname = "foo.com"; }

slide-119
SLIDE 119

Example

class Person { private $name; function setName($name) { $this->name = $name; } function getName() { return $this->name; } }; $judy = new Person(); $judy->setName("Judy"); $joe = new Person(); $joe->setName("Joe"); print $judy->getName() . "\n"; //print Judy print $joe->getName(). "\n"; //print Joe

slide-120
SLIDE 120

Static properties

class MyUniqueIdClass { static $idCounter = 0; public $uniqueId; function __construct() { self::$idCounter++; $this->uniqueId = self::$idCounter; self: refer to the current class $this->uniqueId = self::$idCounter; } } $obj1 = new MyUniqueIdClass(); print $obj1->uniqueId ; //print 1 $obj2 = new MyUniqueIdClass(); print $obj2->uniqueId ; //print 2

slide-121
SLIDE 121

POLYMORPHISM

  • Single class inheritance

– like Java

  • Multiple interface implementations

Final keyword – Final keyword

class Child extends Parent { ... } class A implements B, C, ... { ... } interface I1 extends I2, I3, ... { ... }

slide-122
SLIDE 122

<?php class Auth { function Auth() { mysql_connect('localhost', 'user', 'password'); mysql_select_db('my_own_bookshop'); } public function addUser($email, $password) { $q = ' INSERT INTO users(email, passwd) VALUES (“ '. $email. ‘ ", “ '. sha1($password).‘ ") '; mysql_query($q); }

slide-123
SLIDE 123

public function authUser($email, $password) { $q = ' SELECT * FROM users WHERE email=“ '. $email. ' " AND passwd =“ '. sha1($password). ' " '; $r = mysql_query($q); $r = mysql_query($q); if (mysql_num_rows($r) == 1) { return TRUE; } else { return FALSE; } } } ?>

slide-124
SLIDE 124

Autoload

  • When writing object-oriented code, it is often

customary to put each class in its own source file.

  • Using the _autoload() function (one per
  • Using the _autoload() function (one per

application) a class can be included at run- time

  • The system implicitily passes the name of the

missed class as a parameter of the function

slide-125
SLIDE 125

Myclass.php <?php function __autoload($class_name) { require_once($_SERVER["DOCUMENT_ROOT"] . "/classes/$class_name.php"); } ?> general.inc autoload called if MyClass must be placed in /classes directory

file has same name of the class

<?php class MyClass { function printHelloWorld() { print "Hello, World\n"; } } ?> Myclass.php <?php require_once "general.inc"; $obj = new MyClass(); // calls __autoload $obj->printHelloWorld(); ?> main.php if MyClass is not defined

slide-126
SLIDE 126

Reflection

  • Allows to have class information at run-time
  • Just an example

<?php class C { function F() { print "Hello, World\n"; } } ReflectionClass::export("C"); ?> …

  • Constants [0] { }
  • Static properties [0] { }
  • Static methods [0] { }
  • Properties [0] { }
  • Methods [1] {

Method [ public method F ] …

slide-127
SLIDE 127

Example: delegate pattern

slide-128
SLIDE 128

PHP Communication

string file_get_contents ( string $filename [ …]) Reads entire file into a string

,7 % 4 .! * ( 142< %( $$-%%(*- ; ( ( ###*( ( " PGG? % $$-%###*( (*- ; ( ( ###*( ( " PGG?3 % $$- )###*( (*- ; ( ( *( ( " 1G? $$-%") Q *( (*- ; ( ( *( ( " 1G?3 $$- )") Q *( (*- 7/

slide-129
SLIDE 129

Example

  • Flickr is a web site that allows to share

personal photos

  • Free account for 90 days

API with different formats

  • API with different formats

– Request: REST,XML-RPC,SOAP – Reply: REST,XML-RPC,SOAP,JSON,PHP

slide-130
SLIDE 130

Flickr’s application end-points

  • http://api.flickr.com/services/rest/
  • http://api.flickr.com/services/soap/
  • http://api.flickr.com/services/xmlrpc/
  • http://api.flickr.com/services/upload/
  • http://api.flickr.com/services/upload/
  • http://api.flickr.com/services/replace/
slide-131
SLIDE 131

% ) &(. 7$)))9/*)))

  • REST format is the simplest way; it uses the HTTP POST method

CLIENT SERVER ; !() ;<3G!R02=;?6!3K8?!B3KF!?P? >

slide-132
SLIDE 132

Example of API call

flickr.photos.getInfo

api_key (Mandatory) Your API application key.

In Parameters:

Your API application key. photo_id (Mandatory) The id of the photo to get information for. secret (optional) The secret for the photo. If the correct secret is passed then permissions checking is skipped, unless photo is shared.

Out Parameters: info with different format…

slide-133
SLIDE 133

Example of reply

slide-134
SLIDE 134

An example:

invoking a REST end-point from PHP code

( > $&> / >SCC:'TU'T'TC>! >(%> / >& %4>! > %$> / >>! >(> / > % $>!

  • $ (

Parameters "

  • Reply in php serial format

% ( &/. $ ( @A"&>>". " -% ) &(.7-( >9>!$ (

% ) &(.7 $&SCC:'TU'T'TC9(%& %49 %$9( % $

"

  • non-alphanumeric as %

sign two hex digits

  • spaces as plus (+) signs.
  • Join array elements with

a string,

  • & used as glue string

( "

slide-135
SLIDE 135

Serialization

string serialize ( mixed $value ) Generates a storable representation of a value mixed unserialize ( string $str ) Creates a PHP value from a stored representation

slide-136
SLIDE 136

$ans = file_get_contents($url); $ans_obj = unserialize($ans); if ($ans_obj['stat']=='ok') { echo $ans_obj['photo']['id'].'<br>'; echo $ans_obj['photo']['title'] ['_content']; Invoke method Transform format into an associative array echo $ans_obj['photo']['description']['_content']; echo $ans_obj['photo']['dates']['taken']; }