TDP013

PHP

Anders Fröberg, [email protected] Dept. of Computer and Information Science, Linköping University

fredag, 2009 september 18 Outline

● PHP History/background

● Server side scripting

● Hello World example

● Basic syntax

● What is new in 5.3

● Database drive web applications in PHP

● SOAP and REST

fredag, 2009 september 18 History/Background

● Created by in 1995 – PHP/IF Personal Home Page / Forms Interpreter – A set of perl scripts and C -code

● PHP 3 1997 – and Zeev Suraski – Complete re-write

● PHP 4 1998

● PHP 5 2004 July

fredag, 2009 september 18 PHP

● recursive acronym "PHP: Hypertext Preprocessor"

● or "Pretty Hypertext Preprocessor".

● Used for server side applications

● LAMP – Linux, Apache, MySQL, PHP

● WAMP – Windows, Apache, MySQL, PHP

● WIMP – Windows, IIS, MySQL, PHP fredag, 2009 september 18 Server Side Scripting/ Client Side Server Side HTML,CSS, PHP/JSP/ASP/SQL JavaScript

HTTP Request (URL http://www.ida.liu.se) Web server Databas e server

HTTP Response HTML/CSS/JavaScript

fredag, 2009 september 18 HTTP Request

● A file request with optional arguments

● 2 types of Request – GET

● File and arguments encoded in the URL – http://www.hotmail.com/viewMails.asp? login=anders&password=NisseLasse – POST

● File request – Arguments passed as a stream afterwards – Not visible in the URL fredag, 2009 september 18 Step-by-Step request

● Users types in a URL hits enter

● The web browser send the request to the server

● The web server receives the request and looks up the file – If the file exists send it to the browser – If not send a 404 error

● The web browser receives the file and renders it (nicely)

fredag, 2009 september 18 Step-by-Step request ● Users types in a URL hits enter

● The web browser send the request to the server

● The web server receives the request and looks up the file – If the file exists send it to the browser – If not send a 404 error – If file has . ending (often other may apply) start at the beginning of the file looks for the blocks that start with and ends with ?> fredag, 2009 september 18 PHP -simple example WEB server

HelloHello h1>

this is normal

this is normal html

html

World print “

World

”; ?> fredag, 2009 september 18 Types

● boolean

● integer

● float

● string

● array

● object

● resource

● NULL fredag, 2009 september 18 Basic Syntax

● Variables

● Can't start with numeric values ($4value = “crap” not valid)

fredag, 2009 september 18 Variables as Variables

fredag, 2009 september 18 Basic Syntax

● Constants (Not changing during execution) define("FOO", "something"); define("FOO2", "something else"); define("FOO_BAR", "something more")

// Invalid constant names define("2FOO", "something");

fredag, 2009 september 18 Basic Syntax If

$b) echo "a is bigger than b"; ?> fredag, 2009 september 18 Basic Syntax If-Else

$b) { echo "a is bigger than b"; } else { echo "a is NOT bigger than b"; } ?>

fredag, 2009 september 18 Basic Syntax If-Elseif-Else

$b) { echo "a is bigger than b"; } elseif ($a == $b) { echo "a is equal to b"; }else { echo "a is NOT bigger than b"; } ?>

fredag, 2009 september 18 Basic Syntax While

while (expr): statement ... endwhile; $i = 1; Equal $i = 1; while ($i <= 10): while ($i <= 10) { echo $i; echo $i++; $i++; } endwhile;

fredag, 2009 september 18 Basic Syntax Do-While

do{ statement ... }while(expression);

$i = 0; do { echo $i; $i++; } while ($i < 10);

// What will print? fredag, 2009 september 18 Basic Syntax For //Example 2 for (expr1; expr2; expr3) for ($i = 1; ; $i++) { if ($i > 10) { statement break; } //Example 1 echo $i; for ($i = 1; $i <= 10; $i++) { } echo $i; //Example 3 } $i = 1; for (; ; ) { if ($i > 10) { break; } echo $i; $i++; } fredag, 2009 september 18 PHP Arrays • A ordered Map • Values and Keys • Can be used as • array • list • hash table • dictionary • stack fredag, 2009 september 18 Arrays

● created with array(); array( [key =>] value , ... ) // key may be an integer or string // value may be any value

$arr = array("foo" => "bar", 12 => true); echo $arr["foo"]; // bar echo $arr[12]; // 1 boolean not true/false but 1/0 fredag, 2009 september 18 Arrays cont.

$arr = array(5 => 1, 12 => 2);

$arr[] = 56; // This is the same as $arr[13] = 56; // at this point of the script

$arr["x"] = 42; // This adds a new element to // the array with key "x"

fredag, 2009 september 18 Arrays cont.

$userinfo = array(); $userinfo['login'] = 'Gurra'; $userinfo['password'] = 'rattnalle'; $userinfo['hobbies']= array('sport','food','movie');

print $userinfo["hobbies"][1]; // what will print

fredag, 2009 september 18 Basic Syntax Foreach

foreach (array_expression as $value) statement foreach (array_expression as $key => $value) statement $arr = array('name'=>'Anders','language'=>'PHP'); foreach ($arr as $value) { print $value; } foreach($arr as $key =>$value) { print $key."=".$value;

} fredag, 2009 september 18 Functions

● function namn(argument1,..argument*) { statements return $return_value; //if one }

function add(value1 , value2){ return value1+value2; } fredag, 2009 september 18 Variable scope

function test() function test() { { echo $a; global $a; } echo $a; test(); } ?> test(); ?>

fredag, 2009 september 18 Variable scope ?>

fredag, 2009 september 18 Functions Arguments

● pass-by value

● pass-by reference

● pass-by default-value

fredag, 2009 september 18 pass-by value vs. pass-by

function inc(&$value) function inc($value) { { $value = $value+1; $value = $value+1; } } $number=8; $number=8; inc($number); inc($number); print $number; //????? print $number; //?????

fredag, 2009 september 18 pass-by default-value

Function makecoffee($type = "cappuccino") { return "Making a cup of $type.\n"; } echo makecoffee(); echo makecoffee("espresso");

fredag, 2009 september 18 Returning values

● using the return statement – return “some value”;

● Returning a reference function &returns_reference() { return $someref; } $newref =& returns_reference();

fredag, 2009 september 18 Classes and Objects

● Objects first occurred in PHP4

● More advanced in PHP5 – New Object Model (total re-write) – Private and Protected Members/Methods – Abstract Classes and Methods – Interfaces – Object Cloning

fredag, 2009 september 18

// method declaration

public function displayVar() { echo $this‐>var; } } ?> fredag, 2009 september 18 Creating an instance

// This can also be done with a variable: $className = 'Foo'; $instance = new $className(); // Foo() ?>

fredag, 2009 september 18 Simple Class Inheritance

• Single class inheritance • used with extends • parent::

fredag, 2009 september 18 Simple Class Inheritance

fredag, 2009 september 18 New features in 5.3

• Lambda functions • Closures

fredag, 2009 september 18 fredag, 2009 september 18 • Lambda functions originate from lambda calculus which was introduced by Alonzo Church and Stephen Cole Kleene in the 1930s.

fredag, 2009 september 18 • Lambda functions originate from lambda calculus which was introduced by Alonzo Church and Stephen Cole Kleene in the 1930s.

• The lambda calculus can be thought of as an idealized, minimalistic programming language. It is capable of expressing any algorithm, and it is this fact that makes the model of functional programming an important one.

fredag, 2009 september 18 • Lambda functions originate from lambda calculus which was introduced by Alonzo Church and Stephen Cole Kleene in the 1930s.

• The lambda calculus can be thought of as an idealized, minimalistic programming language. It is capable of expressing any algorithm, and it is this fact that makes the model of functional programming an important one.

• The lambda calculus provides the model for functional programming. Modern functional languages can be viewed as embellishments to the lambda calculus.

fredag, 2009 september 18 fredag, 2009 september 18 • Implementing the lambda calculus on a computer involves treating "functions" as “first‐class objects”, which raises implementation issues for stack-based programming languages.

fredag, 2009 september 18 • Implementing the lambda calculus on a computer involves treating "functions" as “first‐class objects”, which raises implementation issues for stack-based programming languages.

• Many languages implement lambda functions. These include:

fredag, 2009 september 18 • Implementing the lambda calculus on a computer involves treating "functions" as “first‐class objects”, which raises implementation issues for stack-based programming languages.

• Many languages implement lambda functions. These include:

• Python

fredag, 2009 september 18 • Implementing the lambda calculus on a computer involves treating "functions" as “first‐class objects”, which raises implementation issues for stack-based programming languages.

• Many languages implement lambda functions. These include:

• Python

• C++

fredag, 2009 september 18 • Implementing the lambda calculus on a computer involves treating "functions" as “first‐class objects”, which raises implementation issues for stack-based programming languages.

• Many languages implement lambda functions. These include:

• Python

• C++

• C# (2 different implementations – Second one improved in C# v3.0)

fredag, 2009 september 18 • Implementing the lambda calculus on a computer involves treating "functions" as “first‐class objects”, which raises implementation issues for stack-based programming languages.

• Many languages implement lambda functions. These include:

• Python

• C++

• C# (2 different implementations – Second one improved in C# v3.0)

• JavaScript

fredag, 2009 september 18 fredag, 2009 september 18 • Python Lambda • func = lambda x:x**2

fredag, 2009 september 18 var lambdaFunction=function(x) { return x*10; } document.write(lambdaFunction(100));

fredag, 2009 september 18 • JavaScript: var lambdaFunction=function(x) { return x*10; } document.write(lambdaFunction(100));

fredag, 2009 september 18 Lambda Functions – The PHP Way

function & (parameters) use (lexical vars) { body };

fredag, 2009 september 18 fredag, 2009 september 18 • The goal of PHP’s Lambda funcon implementaon is to allow for the creaon of quick throw‐away funcons.

fredag, 2009 september 18 • The goal of PHP’s Lambda funcon implementaon is to allow for the creaon of quick throw‐away funcons.

• Don’t confuse with “create_funcon()”.

fredag, 2009 september 18 • The goal of PHP’s Lambda funcon implementaon is to allow for the creaon of quick throw‐away funcons.

• Don’t confuse with “create_funcon()”. • These funcons compile at “run‐me”.

fredag, 2009 september 18 • The goal of PHP’s Lambda funcon implementaon is to allow for the creaon of quick throw‐away funcons.

• Don’t confuse with “create_funcon()”. • These funcons compile at “run‐me”.

• These funcons DO NOT compile at “compile‐me”.

fredag, 2009 september 18 • The goal of PHP’s Lambda funcon implementaon is to allow for the creaon of quick throw‐away funcons.

• Don’t confuse with “create_funcon()”. • These funcons compile at “run‐me”.

• These funcons DO NOT compile at “compile‐me”.

• Optcode caches CANNOT cache them.

fredag, 2009 september 18 • The goal of PHP’s Lambda funcon implementaon is to allow for the creaon of quick throw‐away funcons.

• Don’t confuse with “create_funcon()”. • These funcons compile at “run‐me”.

• These funcons DO NOT compile at “compile‐me”.

• Optcode caches CANNOT cache them. • Bad pracce.

fredag, 2009 september 18 Closures

fredag, 2009 september 18 fredag, 2009 september 18 • Lambda functions MUST be first-class objects.

fredag, 2009 september 18 • Lambda functions MUST be first-class objects. • Funarg, meaning “functional argument”, is a problem in computer science where a “stack-based programming language” has difficulty implementing functions as “first- class objects”.

fredag, 2009 september 18 • Lambda functions MUST be first-class objects. • Funarg, meaning “functional argument”, is a problem in computer science where a “stack-based programming language” has difficulty implementing functions as “first- class objects”.

• The problem is when the body of a function refers to a variable from the environment that it was created but not the environment of the function call.

fredag, 2009 september 18 • Lambda functions MUST be first-class objects. • Funarg, meaning “functional argument”, is a problem in computer science where a “stack-based programming language” has difficulty implementing functions as “first- class objects”.

• The problem is when the body of a function refers to a variable from the environment that it was created but not the environment of the function call.

• Standard Solutions:

fredag, 2009 september 18 • Lambda functions MUST be first-class objects. • Funarg, meaning “functional argument”, is a problem in computer science where a “stack-based programming language” has difficulty implementing functions as “first- class objects”.

• The problem is when the body of a function refers to a variable from the environment that it was created but not the environment of the function call.

• Standard Solutions: • Forbid such references.

fredag, 2009 september 18 • Lambda functions MUST be first-class objects. • Funarg, meaning “functional argument”, is a problem in computer science where a “stack-based programming language” has difficulty implementing functions as “first- class objects”.

• The problem is when the body of a function refers to a variable from the environment that it was created but not the environment of the function call.

• Standard Solutions: • Forbid such references. • Create closures.

fredag, 2009 september 18 fredag, 2009 september 18 • PHP 5.3 introduces a new keyword ‘use’.

fredag, 2009 september 18 • PHP 5.3 introduces a new keyword ‘use’.

• Use this new keyword when creating a lambda function to define what variables to import into the lambda functions scope – This creates a Closure.

fredag, 2009 september 18 Closures – The “use” Keyword

$config=array('paths'=>array('examples'=>'c:/php/projects/ examples/')); $fileArray=array('example1.php','example2.php','exampleImage.jpg');

$setExamplesPath=function($file) use($config) { return $config['paths']['examples'].$file; };

print_r(array_map($setExamplesPath,$fileArray) );

fredag, 2009 september 18 Closures – The “use” Keyword

Array ( [0] => c:/php/projects/examples/example1.php [1] => c:/php/projects/examples/example2.php [2] => c:/php/projects/examples/exampleImage.jpg )

fredag, 2009 september 18 Lambda functions as anonymous functions $config=array('paths'=>array('examples'=>'c:/php/projects/ examples/')); $fileArray=array('example1.php','example2.php','exampleImage.jpg '); print_r(array_map ( function($file) use($config) { return $config['paths']['examples'].$file; }, $fileArray ));

fredag, 2009 september 18 Lambda functions as anonymous functions

Array ( [0] => c:/php/projects/examples/example1.php [1] => c:/php/projects/examples/example2.php [2] => c:/php/projects/examples/exampleImage.jpg )

fredag, 2009 september 18 fredag, 2009 september 18 • Variables passed into the “use” block are copied in by default – This is the expected PHP behaviour.

fredag, 2009 september 18 • Variables passed into the “use” block are copied in by default – This is the expected PHP behaviour. • You can cause a variable to be imported by reference the same way you do when defining referenced parameters in function declarations.

fredag, 2009 september 18 • Variables passed into the “use” block are copied in by default – This is the expected PHP behaviour. • You can cause a variable to be imported by reference the same way you do when defining referenced parameters in function declarations. • The PHP 5 pass by reference for objects rule still applies.

fredag, 2009 september 18 Reference Variable Import

$config=array('paths'=>array('examples'=>'c:/php/projects/ examples/')); $fileArray=array('example1.php','example2.php','exampleImage.jpg');

$setExamplesPath=function($file) use(&$config) { return $config['paths']['examples'].$file; };

print_r(array_map($setExamplesPath,$fileArray) );

Why ?? fredag, 2009 september 18 • A lambda function can be created at any point in your application, except in class declarations.

• Example: class foo { public $lambda=function() { return 'Hello World'; }; public function __construct() { print $this->lambda(); } } new foo();

Parse error: syntax error, unexpected T_FUNCTION in D: \Development\www\php5.3\lambda\5.php on line 4 fredag, 2009 september 18 Lifecycle

class foo { public $lambda=null; public function __construct() { $this->lambda=function() {return 'Hello World';}; } } $foo=new foo(); var_dump($foo); $lambda=$foo->lambda; unset($foo); var_dump($foo); print $lambda(); object(foo)#1 (1) { ["lambda"]=> object(Closure)#2 (0) { } } NULL Hello World fredag, 2009 september 18 Lifecycle – Objects

class foo { public $bar="Bar\r\n"; public function __construct(){print "__construct()\r\n“;} public function __destruct(){print "__destruct()\r\n“;} public function getBarLambda() { return function(){return $this->bar;}; } } $foo=new foo(); $bar=$foo->getBarLambda(); __construct() print $bar(); Bar unset($foo); NULL var_dump($foo); Bar print $bar(); __destruct() unset($bar); Fatal error Function name must be a string in D:\Development\www print $bar(); \php5.3\lambda\8.php on line 31 fredag, 2009 september 18 fredag, 2009 september 18 • If a closure exists with a reference to an object’s method or property, that object is not completely destroyed when unset.

fredag, 2009 september 18 • If a closure exists with a reference to an object’s method or property, that object is not completely destroyed when unset. • __destruct() is NOT called until the closure is destroyed.

fredag, 2009 september 18 • If a closure exists with a reference to an object’s method or property, that object is not completely destroyed when unset. • __destruct() is NOT called until the closure is destroyed.

• The unset object CANNOT be used in this situation as it will be considered a null value by anything trying to access it outside the closure environment.

fredag, 2009 september 18 fredag, 2009 september 18 • Lambda Functions are Closures because they automatically get bound to the scope of the class that they are created in.

fredag, 2009 september 18 • Lambda Functions are Closures because they automatically get bound to the scope of the class that they are created in. • $this is not always needed in the scope.

fredag, 2009 september 18 • Lambda Functions are Closures because they automatically get bound to the scope of the class that they are created in. • $this is not always needed in the scope. • Removing $this can save on memory.

fredag, 2009 september 18 • Lambda Functions are Closures because they automatically get bound to the scope of the class that they are created in. • $this is not always needed in the scope. • Removing $this can save on memory. • You can block this behaviour by declaring the Lambda Function as static.

fredag, 2009 september 18 Forms in html

● GET and POST request –

● Login.php?username=data&password=data

fredag, 2009 september 18 Form in PHP

● Respond to html form

● Access form fields – Built in arrays

● $_GET[“password”] ● $_POST[“password”]

fredag, 2009 september 18 Database support

● MySql – $dbc = mysql_connect($server,$user,$password) – mysql_select_db($databasename,$dbc) – mysql_query(“select * from users”,$dbc) – Results from database $result=mysql_query($sql,$dbc); while($row= mysql_fetch_array($result)){ print “{$row[“user_name”]}; } fredag, 2009 september 18 User control

● Control users time on the website – From log in to log out – No hotmail bugs – Session

● Built in array for storing user information ● $_SESSION ● $_SESSION[“logged_in”]=1 ● If($_SESSION[“logged_in”]==1) – User logged in fredag, 2009 september 18 Lets build a Web

● Steps – Login-in form – vadlidation – main page (when logged in)

fredag, 2009 september 18 Login form (index.html) Username:

Password: Login

fredag, 2009 september 18 doLogin.php

$connection =mysql_connect(“server” .”username”,”password”,”dbname”);

$username=$_POST[“username”];

$password=$_POST[“password”];

$password_digets=md5(trim($password));

$query = “SELECT password FROM users WHERE

user_name= '{$username}' AND password= '{$password_digets}'”;

if(!$result = mysql_query($query,$connection))

die(“DB error”);

if (mysql_num_rows($result) != 1)

header(“Location: index.html”); // misslyckad inloggning

header(“Location:main.php”);// lyckad inloogning fredag, 2009?> september 18 doLogin.php

..... if (mysql_num_rows($result) != 1){ header(“Location: index.html”); // misslyckad inloggning exit(); }else $_SESSION[“username”]= $username; $_SESSION[“logedin”]=true; header(“Location:main.php”);// lyckad inloogning ?>

fredag, 2009 september 18 main.php

Välkommen

fredag, 2009 september 18 Is there a problem

$query = “SELECT password FROM users WHERE user_name= '{$username}' AND password= '{$password_digets}'”; if(!$result = mysql_query($query,$connection))

fredag, 2009 september 18 • There is a lot of web application with interesting data • I have a application that I like to share functions in

68 fredag, 2009 september 18 • Screen Scraping • A program extracts data from the display output of another program • Web Scraping • Find information in the HTML on a web page • Used by web crawlers and search engines

69 fredag, 2009 september 18