78
PHP Ensky / 林宏昱

2014 database - course 2 - php

Embed Size (px)

DESCRIPTION

 

Citation preview

Page 1: 2014 database - course 2 - php

PHP

Ensky / 林宏昱

Page 2: 2014 database - course 2 - php

Browser sends HTTP request

GET /enskylin HTTP/1.1

Host: www.facebook.com

HTTP/1.1 200 OK

HTML

Page 3: 2014 database - course 2 - php

Load data from database

GET /enskylin HTTP/1.1

Host: www.facebook.com

HTTP/1.1 200 OK

HTML

Page 4: 2014 database - course 2 - php

generate HTML

GET /enskylin HTTP/1.1

Host: www.facebook.com

HTTP/1.1 200 OK

HTML

Page 5: 2014 database - course 2 - php

HTTP response to browser

GET /enskylin HTTP/1.1

Host: www.facebook.com

HTTP/1.1 200 OK

HTML

Page 6: 2014 database - course 2 - php

CGI and Web server

Web server

CGI

HTTP Request

stdin + env

stdout

HTTP Response + BODY

HTTP request

body

HTTP request header

HTTP response

head + body

Page 7: 2014 database - course 2 - php
Page 8: 2014 database - course 2 - php

What's PHP

• Rasmus Lerdorf, Danmark wrote the first version in 1995, use PHP to maintain his homepage

• Originally stood for "Personal Home Page Tools"

• It stands for PHP: Hypertext Preprocessor now

Page 9: 2014 database - course 2 - php

What can PHP do

• Although PHP is an "hypertext preprocessor"you still can use it to do nearly anything you can do in other language, not just writing a web page

C++, JAVA, Python, …

• You can use PHP to write a web server, BBS crawler, NP homework, even a win32 program

Page 10: 2014 database - course 2 - php

Hello world

the same as

#include<iostream>

using namespace std;

int main () {

cout << "Hello world!";

return 0;

}

in C++

<?php

echo "Hello world!";

?>

OR

Hello world!

Page 11: 2014 database - course 2 - php

PHP at a glance

Page 12: 2014 database - course 2 - php

Variables

$helloWorld = "hello world";

echo $helloWorld;

echo $nonExistVar;

PHP Notice: Undefined variable: nonExistVar

• Variables starts with a $ (dollar) sign

• No reserved word. ($if, $else is okay)

• The other rules is the same as C/C++

Page 13: 2014 database - course 2 - php

Types

• Basic

– Boolean -> TRUE / True / true / FALSE / False / false

– Integer -> -(2^n) ~ 2^n - 1, n = 32 or 64overflow: integer to float conversion

– Float -> IEEE 64bit format

– String

• Complex

– Array

– Object

Page 14: 2014 database - course 2 - php

Type verification

var_dump($variable) // can print out the type of $variable

var_dump(2147483647);

// int(2147483647)

var_dump(2147483648);

// float(2147483648)

var_dump(

array(1,2,3)

);

array(3) {

[0]=> int(1)

[1]=> int(2)

[2]=> int(3)

}

Page 15: 2014 database - course 2 - php

Strings

$string1 = "this is a string\n!";

// this is a string

// !

$string2 = 'this is a string, too\n!';

// this is a string, too\n!

$string3 = $string1 . " and " . $string2;

// this is a string

// ! and this is a string, too\n!

Page 16: 2014 database - course 2 - php

Variables in String

$score = 95;

echo "Ensky's score is: " . $score;

echo "Ensky's score is: {$score}";

// Ensky's score is: 95

echo 'Ensky\'s score is: {$score}";

// Ensky's score is: {$score}

// not work with expression

echo "Hi {1+1}"; // Hi {1+1}

Page 17: 2014 database - course 2 - php

Strings (cont'd)

There is no "char type"

$string = "this is a string!";

var_dump($string);

// string(17) "this is a string!"

var_dump($string[0]);

// string(1) "t"

$string[0] = 'T';

echo $string;

// This is a string!

Page 18: 2014 database - course 2 - php

Implicitly type conversion

In PHP, type conversions are implicitly.

BEWARE OF IT!!

var_dump("123" + 456);

// int(579)

var_dump(456 + "1 apple a day keeps…");

// int(457)

var_dump(456 + "1,000");

// int(457)

Page 19: 2014 database - course 2 - php

Explicitly type conversion

$score = 60;

var_dump( (float) $score);

// float(60)

var_dump( (string) $score);

// string(2) "60"

var_dump( (bool) $score);

// bool(true)

Page 20: 2014 database - course 2 - php

== and ===

$a == $b

TRUE if $a is equal to $b after type juggling.

var_dump( 123 == "123" );

// bool(true)

var_dump( "0" == "0.00" );

// bool(true)

var_dump( "0" == 0 );

// bool(true)

Page 21: 2014 database - course 2 - php

== and ===

var_dump( "0" == null );

// bool(false)

var_dump( "0" == false );

// bool(true)

var_dump( null == false );

// bool(true) !!!!!!

var_dump( "0" == false && false == "" );

// bool(true)

var_dump( "0" == "" );

// bool(false) !!!!!!

Page 22: 2014 database - course 2 - php

== and ===

We can use === to avoid unexpected equality

var_dump( "0" === null );

// bool(false)

var_dump( "0" === false );

// bool(false)

var_dump( false === "" );

// bool(false)

var_dump( "0" === false && false === "" );

// bool(false)

var_dump( "0" === "" );

// bool(false)

Page 23: 2014 database - course 2 - php

== and ===

• $a == $b EqualTRUE if $a is equal to $b after type juggling.

• $a === $b IdenticalTRUE if $a is equal to $b, and they are of the same type.

• Note: var_dump( 123 === "123" );// bool(false)

http://tw2.php.net/ternary

Page 24: 2014 database - course 2 - php

Variable scopes in C

in C++, { } introduces a variable scope

for example

{

int a = 0;

}

cout << a << endl;

// reports error, a is in the inside scope

Page 25: 2014 database - course 2 - php

Variable scopes in PHP

in PHP, only Function introduces a new scope

{

$a = 1;

}

echo $a;

// 1

Page 26: 2014 database - course 2 - php

Variable scopes in PHP

in PHP, only Function introduces a new scope

function setA () {

$a = 1; // local variable

}

function printA () {

echo $a; // no, undefined $a

}

setA();

printA();

// PHP Notice: Undefined variable: a

Page 27: 2014 database - course 2 - php

Variable scopes in PHP

Use global keyword to access the global variable

AVOID!!

function printA () {

global $a;

echo $a;

}

$a = 1;

printA();

// 1

Page 28: 2014 database - course 2 - php

functions in PHP

PHP's function acts like C/C++

function fib ($n) {

return $n <= 2 ?

1 : fib($n-1) + fib($n-2);

}

echo fib(9);

// 34

Page 29: 2014 database - course 2 - php

functions in PHP

Default function arguments

function printScore($score = 0) {

echo "your score is: {$score}";

}

printScore();

// your score is 0

printScore(100);

// your score is 100

Page 30: 2014 database - course 2 - php

Arrays

• PHP's array is very powerful, hence very inefficient

• You can use it like

– Array in C / ArrayList in Java / List in Python

– Map in C / HashMap in Java / Dictionary in Python

• With PHP's powerful built-in array functions, array can easily becomes many data structure like Dequeue, Queue, Stack

• You can put anything in array, even another array, or an object;

Page 31: 2014 database - course 2 - php

Arrays

You can use like a simple C-style array

$scores = array(30, 35, 45, 25);

print_r($scores);

/* Array

(

[0] => 30

[1] => 35

[2] => 45

[3] => 25

) */

key

value

Page 32: 2014 database - course 2 - php

Arrays

Totally the same as

$scores = array(0 => 30, 1 => 35, 2 => 45, 3 => 25);

print_r($scores);

/* Array

(

[0] => 30

[1] => 35

[2] => 45

[3] => 25

) */

key

value

Page 33: 2014 database - course 2 - php

Arrays

or a HashMap

$menu = array(

'beef noodles' => 260,

'noodles' => 60,

'beef' => 200

);

echo "price of beef is: $" . $menu['beef'];

// price of beef is: $200

key

value

Page 34: 2014 database - course 2 - php

Arrays

or act as an queue$queue = array();$queue[] = '1';$queue[] = '2';$queue[] = '3';echo array_shift($queue);// 1print_r($queue);/* Array(

[0] => 2[1] => 3

) */

auto key

value

Page 35: 2014 database - course 2 - php

Arrays

or act as an stack$queue = array();$queue[] = '1';$queue[] = '2';$queue[] = '3';echo array_pop($queue);// 3print_r($queue);/* Array(

[0] => 1[1] => 2

) */

auto key

value

Page 36: 2014 database - course 2 - php

Arrays

hold a structured document

$persion = array(

'name' => 'ensky',

'age' => 23,

'works' => array(

'NCTU computer science TA',

'2014 Database TA'

)

);

keyvalue

value

no key, auto assign one

Page 37: 2014 database - course 2 - php

Control Structures

• Nearly the same as C++

• if, else if, else

• switch, case, default

• do … while

• while

• for

• break, continue

• return

Page 38: 2014 database - course 2 - php

Control Structures

Foreach:

$array = array(1, 2, 3);

foreach ($array as $value) {

echo $value . " ";

}

// 1 2 3

Page 39: 2014 database - course 2 - php

Control Structures

Foreach:

$array = array('a' => 'apple', 'b' => 'banana');

foreach ($array as $key => $value) {

echo "{$key}:{$value} ";

}

// a:apple b:banana

Page 40: 2014 database - course 2 - php

PHP and HTML

Let's start with Hello world

Page 41: 2014 database - course 2 - php

PHP & HTML - Hello world

Let's start with Hello world

== index.php ==

<!doctype html><html lang="en">

<head><meta charset="utf-8">

<title>Hello world! Title</title>

</head>

<body>

<p>Hello world!</p></body>

</html>

Page 42: 2014 database - course 2 - php

Recall PHP Hello world

the same as

#include<iostream>

using namespace std;

int main () {

cout << "Hello world!";

return 0;

}

in C++

<?php

echo "Hello world!";

?>

OR

Hello world!

Page 43: 2014 database - course 2 - php

PHP & HTML – print variable

<?php $name = 'ensky'; ?>

<body>

<p>Hello world! <?php echo $name; ?></p>

<p>Hello world! <?= $name ?></p></body>

Page 44: 2014 database - course 2 - php

PHP & HTML – print data

<?php

$dict = array('a' => 'apple', 'b' => 'banana');

?>

<?php foreach ($dict as $key => $val): ?>

<p><?= $key ?> : <?= $val ?></p>

<?php endforeach; ?>

Page 45: 2014 database - course 2 - php

HTML Forms

Page 46: 2014 database - course 2 - php

HTML forms

How to create a form in HTML?

1. create a form tag

<form action="login.php" method="POST">

</form>

where to send GET or POST?

Page 47: 2014 database - course 2 - php

HTML forms

How to create a form in HTML?

2. put some input

<form action="login.php" method="POST">

<input type="text" name="email">

<input type="password" name="password">

</form>

http://www.w3schools.com/tags/att_input_type.asp

Page 48: 2014 database - course 2 - php

HTML forms

How to create a form in HTML?

2. put some inputs

<form action="login.php" method="POST">

<input type="text" name="email">

<input type="password" name="password">

<button type="submit">免費註冊</button>

</form>

Page 49: 2014 database - course 2 - php

POST /login.php HTTP/1.1Host: your_hostname

<form action="login.php" method="POST"><input type="text" name="email"><input type="password" name="password"><button type="submit">免費註冊</button>

</form>

[email protected]&password=nctu5566

/login.php

Page 50: 2014 database - course 2 - php

[email protected]&password=nctu5566

/login.php

In login.php-----<?phpecho $_POST['email'];echo $_POST['password'];?>

POST /login.php HTTP/1.1Host: your_hostname

Page 51: 2014 database - course 2 - php

HTTP & states

Page 52: 2014 database - course 2 - php

HTTP is a stateless protocol

Page 53: 2014 database - course 2 - php

When you open a browser,navigate to a url

Page 54: 2014 database - course 2 - php

HTTP Request

Page 55: 2014 database - course 2 - php

HTTP response

Page 56: 2014 database - course 2 - php

and it is done.

Page 57: 2014 database - course 2 - php

How do we preserve the "state"?

login or not?

who are you?

what did you buy?

Page 58: 2014 database - course 2 - php

Cookie!

• HTTP protocol defined a spec called "cookie"

• which can help server to identify clients

HOW?

Page 59: 2014 database - course 2 - php

client request

HTTP Request

Page 60: 2014 database - course 2 - php

server response with set-cookie header

HTTP responseSet-Cookie: name=ensky

HTML …

Server asked me to save the cookie!

Page 61: 2014 database - course 2 - php

The next client requestwill bring the cookie set by server

HTTP Requestcookie: name=ensky

Page 62: 2014 database - course 2 - php

Server is able to identify which client it is.

HTTP Requestcookie: name=ensky

Oh! you're ensky

Page 63: 2014 database - course 2 - php

Cookie's problem

• However, Cookie identification is too weak!

• Anyone who can make a fake identification

HTTP Requestcookie: name=ensky

Oh! you're ensky

I'm Cracker

Page 64: 2014 database - course 2 - php

Session

• One approach is session

• Server gives client a "temporally key"

HTTP Request

Page 65: 2014 database - course 2 - php

After the request, server will generate the temporarily key

session name

0aj9 ensky

s4df dy93

HTTP Request

generate a temp key, expire in a short time

Page 66: 2014 database - course 2 - php

Response with session(temp key)

HTTP Request

HTTP responseSet-Cookie: session=0aj9

HTML …

session name

0aj9 ensky

s4df dy93

Page 67: 2014 database - course 2 - php

Server can then identify successfully by correct key

HTTP Requestcookie: session=0aj9

Oh! you're ensky

session name

0aj9 ensky

s4df dy93

Page 68: 2014 database - course 2 - php

Use session

Set

------

<?php

session_start();

$_SESSION['name'] = 'ensky';

Page 69: 2014 database - course 2 - php

Use session

Get

------

<?php

session_start();

echo $_SESSION['name'];

Page 70: 2014 database - course 2 - php

Use session

Destroy

------

<?php

session_start();

$_SESSION = array();

session_destroy();

Page 71: 2014 database - course 2 - php

Use session

• Note:session_start(); must be call before any HTML output

– why?

Page 72: 2014 database - course 2 - php

Practice

• write a webpage

– login (using predefined username / password)

• output login error when input wrong username or password

– echo out current DateTime(ex: 2014/3/4 9:55:54) using PHP date() function

• see PHP doc

• shows only when user is logged-in successfully

– logout

• after logout, user cannot use any function without login

• Just practice, no need to hand in

Page 73: 2014 database - course 2 - php

Appendix

Page 74: 2014 database - course 2 - php

Run PHP script

• Since PHP is a server-side CGI, you cannot just open PHP script in your browser

• After written PHP script by IDEs I suggested last week, you should put it in CS web server, and reach it by http://people.cs.nctu.edu.tw/~your_id/file_name.php

or your own webserver and reach it by http://localhost/file_name.php

Page 75: 2014 database - course 2 - php

functions in PHP

Defines as anonymous function

$fib = function ($n) { … }

echo $fib(9);

inner function

function a () {

$n = 0;

$b = function () use ($n) {

// you can use $n here

};

}

since PHP 5.3

Page 76: 2014 database - course 2 - php

functions in PHP

Reference arguments

function addN (& $n) {

$n++;

}

$n = 0;

addN($n);

echo $n;

// 1

Page 77: 2014 database - course 2 - php

Redirect

• how to redirect to another webpage?

<?php

header('location: another_webpage.php');

exit;

note: you must call header before any HTML output, just like session_start();

Page 78: 2014 database - course 2 - php

PHP Module

In PHP, you can import other file into a file

lib.php

-----

<?php

function fib($a) { return … }

page.php

<?php

require_once "lib.php";

echo fib(3);

http://www.php.net/manual/es/function.include.php