SlideShare una empresa de Scribd logo
1 de 78
Descargar para leer sin conexión
PHP
Ensky / 林宏昱
Browser sends HTTP request
GET /enskylin HTTP/1.1
Host: www.facebook.com
HTTP/1.1 200 OK
HTML
Load data from database
GET /enskylin HTTP/1.1
Host: www.facebook.com
HTTP/1.1 200 OK
HTML
generate HTML
GET /enskylin HTTP/1.1
Host: www.facebook.com
HTTP/1.1 200 OK
HTML
HTTP response to browser
GET /enskylin HTTP/1.1
Host: www.facebook.com
HTTP/1.1 200 OK
HTML
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
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
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
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!
PHP at a glance
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++
Types
• Basic
– Boolean -> TRUE / True / true / FALSE / False / false
– Integer -> -(2^n) ~ 2^n - 1, n = 32 or 64
overflow: integer to float conversion
– Float -> IEEE 64bit format
– String
• Complex
– Array
– Object
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)
}
Strings
$string1 = "this is a stringn!";
// this is a string
// !
$string2 = 'this is a string, toon!';
// this is a string, toon!
$string3 = $string1 . " and " . $string2;
// this is a string
// ! and this is a string, toon!
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}
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!
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)
Explicitly type conversion
$score = 60;
var_dump( (float) $score);
// float(60)
var_dump( (string) $score);
// string(2) "60"
var_dump( (bool) $score);
// bool(true)
== 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)
== 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) !!!!!!
== 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)
== and ===
• $a == $b Equal
TRUE if $a is equal to $b after type juggling.
• $a === $b Identical
TRUE 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
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
Variable scopes in PHP
in PHP, only Function introduces a new scope
{
$a = 1;
}
echo $a;
// 1
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
Variable scopes in PHP
Use global keyword to access the global
variable
AVOID!!
function printA () {
global $a;
echo $a;
}
$a = 1;
printA();
// 1
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
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
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;
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
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
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
Arrays
or act as an queue
$queue = array();
$queue[] = '1';
$queue[] = '2';
$queue[] = '3';
echo array_shift($queue);
// 1
print_r($queue);
/* Array
(
[0] => 2
[1] => 3
) */
auto key
value
Arrays
or act as an stack
$queue = array();
$queue[] = '1';
$queue[] = '2';
$queue[] = '3';
echo array_pop($queue);
// 3
print_r($queue);
/* Array
(
[0] => 1
[1] => 2
) */
auto key
value
Arrays
hold a structured document
$persion = array(
'name' => 'ensky',
'age' => 23,
'works' => array(
'NCTU computer science TA',
'2014 Database TA'
)
);
key
value
value
no key, auto assign one
Control Structures
• Nearly the same as C++
• if, else if, else
• switch, case, default
• do … while
• while
• for
• break, continue
• return
Control Structures
Foreach:
$array = array(1, 2, 3);
foreach ($array as $value) {
echo $value . " ";
}
// 1 2 3
Control Structures
Foreach:
$array = array('a' => 'apple', 'b' => 'banana');
foreach ($array as $key => $value) {
echo "{$key}:{$value} ";
}
// a:apple b:banana
PHP and HTML
Let's start with Hello world
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>
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!
PHP & HTML – print variable
<?php $name = 'ensky'; ?>
…
<body>
<p>Hello world! <?php echo $name; ?></p>
<p>Hello world! <?= $name ?></p>
</body>
…
PHP & HTML – print data
<?php
$dict = array('a' => 'apple', 'b' => 'banana');
?>
…
<?php foreach ($dict as $key => $val): ?>
<p><?= $key ?> : <?= $val ?></p>
<?php endforeach; ?>
HTML Forms
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?
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
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>
POST /login.php HTTP/1.1
Host: your_hostname
<form action="login.php" method="POST">
<input type="text" name="email">
<input type="password" name="password">
<button type="submit">免費註冊</button>
</form>
email=enskylin@gmail.com&
password=nctu5566
/login.php
email=enskylin@gmail.com&
password=nctu5566
/login.php
In login.php
-----
<?php
echo $_POST['email'];
echo $_POST['password'];
?>
POST /login.php HTTP/1.1
Host: your_hostname
HTTP & states
HTTP is a stateless protocol
When you open a browser,
navigate to a url
HTTP Request
HTTP response
and it is done.
How do we preserve the
"state"?
login or not?
who are you?
what did you buy?
Cookie!
• HTTP protocol defined a spec called "cookie"
• which can help server to identify clients
HOW?
client request
HTTP Request
server response
with set-cookie header
HTTP response
Set-Cookie: name=ensky
HTML …
Server asked me
to save the cookie!
The next client request
will bring the cookie set by server
HTTP Request
cookie: name=ensky
Server is able to identify
which client it is.
HTTP Request
cookie: name=ensky
Oh! you're
ensky
Cookie's problem
• However, Cookie identification is too weak!
• Anyone who can make a fake identification
HTTP Request
cookie: name=ensky
Oh! you're
ensky
I'm Cracker
Session
• One approach is session
• Server gives client a "temporally key"
HTTP Request
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
Response with session(temp key)
HTTP Request
HTTP response
Set-Cookie: session=0aj9
HTML …
session name
0aj9 ensky
s4df dy93
Server can then identify
successfully by correct key
HTTP Request
cookie: session=0aj9
Oh! you're
ensky
session name
0aj9 ensky
s4df dy93
Use session
Set
------
<?php
session_start();
$_SESSION['name'] = 'ensky';
Use session
Get
------
<?php
session_start();
echo $_SESSION['name'];
Use session
Destroy
------
<?php
session_start();
$_SESSION = array();
session_destroy();
Use session
• Note:
session_start(); must be call before any HTML output
– why?
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
Appendix
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
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
functions in PHP
Reference arguments
function addN (& $n) {
$n++;
}
$n = 0;
addN($n);
echo $n;
// 1
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();
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.in
clude.php

Más contenido relacionado

La actualidad más candente

News of the Symfony2 World
News of the Symfony2 WorldNews of the Symfony2 World
News of the Symfony2 World
Fabien Potencier
 

La actualidad más candente (18)

Class 2 - Introduction to PHP
Class 2 - Introduction to PHPClass 2 - Introduction to PHP
Class 2 - Introduction to PHP
 
Sorting arrays in PHP
Sorting arrays in PHPSorting arrays in PHP
Sorting arrays in PHP
 
[PL] Jak nie zostać "programistą" PHP?
[PL] Jak nie zostać "programistą" PHP?[PL] Jak nie zostać "programistą" PHP?
[PL] Jak nie zostać "programistą" PHP?
 
Zend Certification Preparation Tutorial
Zend Certification Preparation TutorialZend Certification Preparation Tutorial
Zend Certification Preparation Tutorial
 
PHP variables
PHP  variablesPHP  variables
PHP variables
 
Introduction to PHP
Introduction to PHPIntroduction to PHP
Introduction to PHP
 
Php Tutorials for Beginners
Php Tutorials for BeginnersPhp Tutorials for Beginners
Php Tutorials for Beginners
 
Symfony 2.0 on PHP 5.3
Symfony 2.0 on PHP 5.3Symfony 2.0 on PHP 5.3
Symfony 2.0 on PHP 5.3
 
PHP Functions & Arrays
PHP Functions & ArraysPHP Functions & Arrays
PHP Functions & Arrays
 
Lecture19-20
Lecture19-20Lecture19-20
Lecture19-20
 
Looping the Loop with SPL Iterators
Looping the Loop with SPL IteratorsLooping the Loop with SPL Iterators
Looping the Loop with SPL Iterators
 
Refactoring using Codeception
Refactoring using CodeceptionRefactoring using Codeception
Refactoring using Codeception
 
Introduction in php
Introduction in phpIntroduction in php
Introduction in php
 
How to count money using PHP and not lose money
How to count money using PHP and not lose moneyHow to count money using PHP and not lose money
How to count money using PHP and not lose money
 
Electrify your code with PHP Generators
Electrify your code with PHP GeneratorsElectrify your code with PHP Generators
Electrify your code with PHP Generators
 
Further Php
Further PhpFurther Php
Further Php
 
News of the Symfony2 World
News of the Symfony2 WorldNews of the Symfony2 World
News of the Symfony2 World
 
Symfony2 - WebExpo 2010
Symfony2 - WebExpo 2010Symfony2 - WebExpo 2010
Symfony2 - WebExpo 2010
 

Similar a 2014 database - course 2 - php

Building an e:commerce site with PHP
Building an e:commerce site with PHPBuilding an e:commerce site with PHP
Building an e:commerce site with PHP
webhostingguy
 
Good Evils In Perl (Yapc Asia)
Good Evils In Perl (Yapc Asia)Good Evils In Perl (Yapc Asia)
Good Evils In Perl (Yapc Asia)
Kang-min Liu
 

Similar a 2014 database - course 2 - php (20)

Web 8 | Introduction to PHP
Web 8 | Introduction to PHPWeb 8 | Introduction to PHP
Web 8 | Introduction to PHP
 
Basic PHP
Basic PHPBasic PHP
Basic PHP
 
Php mysql
Php mysqlPhp mysql
Php mysql
 
php programming.pptx
php programming.pptxphp programming.pptx
php programming.pptx
 
PHP POWERPOINT SLIDES
PHP POWERPOINT SLIDESPHP POWERPOINT SLIDES
PHP POWERPOINT SLIDES
 
PHP
PHP PHP
PHP
 
Introduction to PHP
Introduction to PHPIntroduction to PHP
Introduction to PHP
 
php AND MYSQL _ppt.pdf
php AND MYSQL _ppt.pdfphp AND MYSQL _ppt.pdf
php AND MYSQL _ppt.pdf
 
Introduction in php part 2
Introduction in php part 2Introduction in php part 2
Introduction in php part 2
 
PHP Basic
PHP BasicPHP Basic
PHP Basic
 
Blog Hacks 2011
Blog Hacks 2011Blog Hacks 2011
Blog Hacks 2011
 
Php Lecture Notes
Php Lecture NotesPhp Lecture Notes
Php Lecture Notes
 
Expressions and Operators.pptx
Expressions and Operators.pptxExpressions and Operators.pptx
Expressions and Operators.pptx
 
Quick beginner to Lower-Advanced guide/tutorial in PHP
Quick beginner to Lower-Advanced guide/tutorial in PHPQuick beginner to Lower-Advanced guide/tutorial in PHP
Quick beginner to Lower-Advanced guide/tutorial in PHP
 
Introducation to php for beginners
Introducation to php for beginners Introducation to php for beginners
Introducation to php for beginners
 
03-forms.ppt.pptx
03-forms.ppt.pptx03-forms.ppt.pptx
03-forms.ppt.pptx
 
PHP Powerpoint -- Teach PHP with this
PHP Powerpoint -- Teach PHP with thisPHP Powerpoint -- Teach PHP with this
PHP Powerpoint -- Teach PHP with this
 
Building an e:commerce site with PHP
Building an e:commerce site with PHPBuilding an e:commerce site with PHP
Building an e:commerce site with PHP
 
Php with my sql
Php with my sqlPhp with my sql
Php with my sql
 
Good Evils In Perl (Yapc Asia)
Good Evils In Perl (Yapc Asia)Good Evils In Perl (Yapc Asia)
Good Evils In Perl (Yapc Asia)
 

Más de Hung-yu Lin

2014 database - course 3 - PHP and MySQL
2014 database - course 3 - PHP and MySQL2014 database - course 3 - PHP and MySQL
2014 database - course 3 - PHP and MySQL
Hung-yu Lin
 
2014 database - course 1 - www introduction
2014 database - course 1 - www introduction2014 database - course 1 - www introduction
2014 database - course 1 - www introduction
Hung-yu Lin
 
OpenWebSchool - 11 - CodeIgniter
OpenWebSchool - 11 - CodeIgniterOpenWebSchool - 11 - CodeIgniter
OpenWebSchool - 11 - CodeIgniter
Hung-yu Lin
 
OpenWebSchool - 06 - PHP + MySQL
OpenWebSchool - 06 - PHP + MySQLOpenWebSchool - 06 - PHP + MySQL
OpenWebSchool - 06 - PHP + MySQL
Hung-yu Lin
 
OpenWebSchool - 05 - MySQL
OpenWebSchool - 05 - MySQLOpenWebSchool - 05 - MySQL
OpenWebSchool - 05 - MySQL
Hung-yu Lin
 
OpenWebSchool - 02 - PHP Part I
OpenWebSchool - 02 - PHP Part IOpenWebSchool - 02 - PHP Part I
OpenWebSchool - 02 - PHP Part I
Hung-yu Lin
 
OpenWebSchool - 01 - WWW Intro
OpenWebSchool - 01 - WWW IntroOpenWebSchool - 01 - WWW Intro
OpenWebSchool - 01 - WWW Intro
Hung-yu Lin
 
OpenWebSchool - 03 - PHP Part II
OpenWebSchool - 03 - PHP Part IIOpenWebSchool - 03 - PHP Part II
OpenWebSchool - 03 - PHP Part II
Hung-yu Lin
 
Dremel: interactive analysis of web-scale datasets
Dremel: interactive analysis of web-scale datasetsDremel: interactive analysis of web-scale datasets
Dremel: interactive analysis of web-scale datasets
Hung-yu Lin
 

Más de Hung-yu Lin (11)

2014 database - course 3 - PHP and MySQL
2014 database - course 3 - PHP and MySQL2014 database - course 3 - PHP and MySQL
2014 database - course 3 - PHP and MySQL
 
2014 database - course 1 - www introduction
2014 database - course 1 - www introduction2014 database - course 1 - www introduction
2014 database - course 1 - www introduction
 
OpenWebSchool - 11 - CodeIgniter
OpenWebSchool - 11 - CodeIgniterOpenWebSchool - 11 - CodeIgniter
OpenWebSchool - 11 - CodeIgniter
 
OpenWebSchool - 06 - PHP + MySQL
OpenWebSchool - 06 - PHP + MySQLOpenWebSchool - 06 - PHP + MySQL
OpenWebSchool - 06 - PHP + MySQL
 
OpenWebSchool - 05 - MySQL
OpenWebSchool - 05 - MySQLOpenWebSchool - 05 - MySQL
OpenWebSchool - 05 - MySQL
 
OpenWebSchool - 02 - PHP Part I
OpenWebSchool - 02 - PHP Part IOpenWebSchool - 02 - PHP Part I
OpenWebSchool - 02 - PHP Part I
 
OpenWebSchool - 01 - WWW Intro
OpenWebSchool - 01 - WWW IntroOpenWebSchool - 01 - WWW Intro
OpenWebSchool - 01 - WWW Intro
 
OpenWebSchool - 03 - PHP Part II
OpenWebSchool - 03 - PHP Part IIOpenWebSchool - 03 - PHP Part II
OpenWebSchool - 03 - PHP Part II
 
Dremel: interactive analysis of web-scale datasets
Dremel: interactive analysis of web-scale datasetsDremel: interactive analysis of web-scale datasets
Dremel: interactive analysis of web-scale datasets
 
Google App Engine
Google App EngineGoogle App Engine
Google App Engine
 
Redis
RedisRedis
Redis
 

Último

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

Último (20)

Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
A Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusA Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source Milvus
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelNavi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 

2014 database - course 2 - php

  • 2. Browser sends HTTP request GET /enskylin HTTP/1.1 Host: www.facebook.com HTTP/1.1 200 OK HTML
  • 3. Load data from database GET /enskylin HTTP/1.1 Host: www.facebook.com HTTP/1.1 200 OK HTML
  • 4. generate HTML GET /enskylin HTTP/1.1 Host: www.facebook.com HTTP/1.1 200 OK HTML
  • 5. HTTP response to browser GET /enskylin HTTP/1.1 Host: www.facebook.com HTTP/1.1 200 OK HTML
  • 6. 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
  • 7.
  • 8. 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
  • 9. 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
  • 10. 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!
  • 11. PHP at a glance
  • 12. 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++
  • 13. Types • Basic – Boolean -> TRUE / True / true / FALSE / False / false – Integer -> -(2^n) ~ 2^n - 1, n = 32 or 64 overflow: integer to float conversion – Float -> IEEE 64bit format – String • Complex – Array – Object
  • 14. 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) }
  • 15. Strings $string1 = "this is a stringn!"; // this is a string // ! $string2 = 'this is a string, toon!'; // this is a string, toon! $string3 = $string1 . " and " . $string2; // this is a string // ! and this is a string, toon!
  • 16. 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}
  • 17. 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!
  • 18. 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)
  • 19. Explicitly type conversion $score = 60; var_dump( (float) $score); // float(60) var_dump( (string) $score); // string(2) "60" var_dump( (bool) $score); // bool(true)
  • 20. == 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)
  • 21. == 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) !!!!!!
  • 22. == 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)
  • 23. == and === • $a == $b Equal TRUE if $a is equal to $b after type juggling. • $a === $b Identical TRUE 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
  • 24. 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
  • 25. Variable scopes in PHP in PHP, only Function introduces a new scope { $a = 1; } echo $a; // 1
  • 26. 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
  • 27. Variable scopes in PHP Use global keyword to access the global variable AVOID!! function printA () { global $a; echo $a; } $a = 1; printA(); // 1
  • 28. 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
  • 29. 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
  • 30. 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;
  • 31. 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
  • 32. 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
  • 33. 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
  • 34. Arrays or act as an queue $queue = array(); $queue[] = '1'; $queue[] = '2'; $queue[] = '3'; echo array_shift($queue); // 1 print_r($queue); /* Array ( [0] => 2 [1] => 3 ) */ auto key value
  • 35. Arrays or act as an stack $queue = array(); $queue[] = '1'; $queue[] = '2'; $queue[] = '3'; echo array_pop($queue); // 3 print_r($queue); /* Array ( [0] => 1 [1] => 2 ) */ auto key value
  • 36. Arrays hold a structured document $persion = array( 'name' => 'ensky', 'age' => 23, 'works' => array( 'NCTU computer science TA', '2014 Database TA' ) ); key value value no key, auto assign one
  • 37. Control Structures • Nearly the same as C++ • if, else if, else • switch, case, default • do … while • while • for • break, continue • return
  • 38. Control Structures Foreach: $array = array(1, 2, 3); foreach ($array as $value) { echo $value . " "; } // 1 2 3
  • 39. Control Structures Foreach: $array = array('a' => 'apple', 'b' => 'banana'); foreach ($array as $key => $value) { echo "{$key}:{$value} "; } // a:apple b:banana
  • 40. PHP and HTML Let's start with Hello world
  • 41. 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>
  • 42. 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!
  • 43. PHP & HTML – print variable <?php $name = 'ensky'; ?> … <body> <p>Hello world! <?php echo $name; ?></p> <p>Hello world! <?= $name ?></p> </body> …
  • 44. PHP & HTML – print data <?php $dict = array('a' => 'apple', 'b' => 'banana'); ?> … <?php foreach ($dict as $key => $val): ?> <p><?= $key ?> : <?= $val ?></p> <?php endforeach; ?>
  • 46. 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?
  • 47. 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
  • 48. 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>
  • 49. POST /login.php HTTP/1.1 Host: your_hostname <form action="login.php" method="POST"> <input type="text" name="email"> <input type="password" name="password"> <button type="submit">免費註冊</button> </form> email=enskylin@gmail.com& password=nctu5566 /login.php
  • 50. email=enskylin@gmail.com& password=nctu5566 /login.php In login.php ----- <?php echo $_POST['email']; echo $_POST['password']; ?> POST /login.php HTTP/1.1 Host: your_hostname
  • 52. HTTP is a stateless protocol
  • 53. When you open a browser, navigate to a url
  • 56. and it is done.
  • 57. How do we preserve the "state"? login or not? who are you? what did you buy?
  • 58. Cookie! • HTTP protocol defined a spec called "cookie" • which can help server to identify clients HOW?
  • 60. server response with set-cookie header HTTP response Set-Cookie: name=ensky HTML … Server asked me to save the cookie!
  • 61. The next client request will bring the cookie set by server HTTP Request cookie: name=ensky
  • 62. Server is able to identify which client it is. HTTP Request cookie: name=ensky Oh! you're ensky
  • 63. Cookie's problem • However, Cookie identification is too weak! • Anyone who can make a fake identification HTTP Request cookie: name=ensky Oh! you're ensky I'm Cracker
  • 64. Session • One approach is session • Server gives client a "temporally key" HTTP Request
  • 65. 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
  • 66. Response with session(temp key) HTTP Request HTTP response Set-Cookie: session=0aj9 HTML … session name 0aj9 ensky s4df dy93
  • 67. Server can then identify successfully by correct key HTTP Request cookie: session=0aj9 Oh! you're ensky session name 0aj9 ensky s4df dy93
  • 71. Use session • Note: session_start(); must be call before any HTML output – why?
  • 72. 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
  • 74. 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
  • 75. 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
  • 76. functions in PHP Reference arguments function addN (& $n) { $n++; } $n = 0; addN($n); echo $n; // 1
  • 77. 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();
  • 78. 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.in clude.php