SlideShare uma empresa Scribd logo
1 de 34
Baixar para ler offline
PHP - MySQL
Ensky / 林宏昱
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
How to access database?
• today's topic :D
Establish a connection
(you should set it up during your installation)
(If you use cscc account, then follow the instruction on cscc
MySQL website)
username: root
password: nctu5566
login successfully
Do some Queries
Insert: Create
Select: Read
Update: Update
Delete: Delete
INSERT INTO users (id, pw) VALUES ('jlhuang', 'iLove5566')
Query OK, 1 rows affected
Dealing with Results
Generate the correspond HTML
SELECT * FROM users
100 row in set (0.00 sec)
That's all.
Hello world! - connect
Establish a connection:
$db_host = "host_name";
$db_name = "database_name";
$db_user = "user_name";
$db_password = "password";
$dsn = "mysql:host=$db_host;dbname=$db_name";
$db = new PDO($dsn, $db_user, $db_password);
Hello world! - Insert
SQL
--
INSERT INTO `users` (id, username, gender)
VALUES(1, 'Ensky', 'male')
PHP
--
$sql = "INSERT INTO `users` (id, username, gender)"
. " VALUES(?, ?, ?)";
$sth = $db->prepare($sql);
$sth->execute(array(1, 'ensky', 'male'));
id username gender
1 Ensky male
Hello world! - Select
$sql = "SELECT * FROM `users`"
. " WHERE `username` = ? AND `password` = ?";
$sth = $db->prepare($sql);
$sth->execute(array('ensky', 'nctu5566'));
id username password gender
1 Ensky nctu5566 male
2 Emily sdfasdf female
Hello world! - Retrieve
$sql = "SELECT username, gender FROM `users`"
. " WHERE `username` = ? AND `password` = ?";
$sth = $db->prepare($sql);
$sth->execute(array('ensky', 'nctu5566'));
while ($result = $sth->fetchObject()) {
echo $result->name . $result->gender;
}
// Ensky male
// Emily female
// … id username password gender
1 Ensky nctu5566 male
2 Emily sdfasdf female
Named parameters
$sql = "SELECT username, gender FROM `users`"
. " WHERE `username` = ? AND `password` = ?";
$sth = $db->prepare($sql);
$sth->execute(array('ensky', 'nctu5566'));
is equal to
$sql = "SELECT username, gender FROM `users`"
. " WHERE `username` = :un AND `password` = :pw";
$sth = $db->prepare($sql);
$sth->execute(array(
':un' => 'ensky',
':pw' => 'nctu5566'));
PHP Data Objects
• PDO is an OO style class
• Classes
– PDO
• PDO __construct ( string $dsn, [, string $username [, string
$password ]])
• PDOStatement prepare( string $statement )
• PDOStatement query( string $statement )
– PDOStatement
• bool execute ([ array $input_parameters ] )
• mixed fetchObject ([ string $class_name = "stdClass" [, array
$ctor_args ]] )
Don't use mysql_*
• There are many libraries to help you connect to
MySQL database
– MySQL
– MySQLi
– PDO
• If your books recommends you to use mysql_xxx
functions, throws it.
Don't use mysql_*
• What's the problem of mysql_ functions?
– It is deprecated in PHP 5.5.0, and will be removed in PHP6
– SQL Injection problem
• no prepared statement
– Only support MySQL(PDO supports 12 different databases)
What's SQL injection?
Simple query(use mysql ext)
login_action.php
--
<?php
mysql_connect($db_host, $db_user, $db_password);
mysql_select_db($dn_name);
$result = mysql_query(
"SELECT * FROM `users`"
." WHERE `email` = '{$_POST['email']}'"
." AND `password = '{$_POST['password']}'"
);
// …
Simple query(use mysql ext)
login_form.php
login_action.php
--
$result = mysql_query(
"SELECT * FROM `users`"
." WHERE `email` = '{$_POST['email']}'"
." AND `password = '{$_POST['password']}'"
);
Simple query(use mysql ext)
login_form.php
login_action.php
--
$result = mysql_query(
"SELECT * FROM `users`"
." WHERE `email` = 'enskylin@gmail.com'"
." AND `password = 'nctu5566'"
);
Simple query(use mysql ext)
$result = mysql_query(
"SELECT * FROM `users`"
." WHERE `email` = 'enskylin@gmail.com'"
." AND `password = 'nctu5566'"
);
SELECT * FROM `users`
WHERE `email` = 'enskylin@gmail.com'
AND `password` = 'nctu5566'
SQL injection
"--" in SQL represents "comments"
SELECT * FROM `users` -- I want to select all from user
SELECT * FROM `users` -- today is a good day
SQL injection
If a cracker knows your query logic:
SELECT * FROM `users`
WHERE `email` = 'user_account'
AND `password = 'user_password'
give a try:
user_account = ' OR 1=1 --
SELECT * FROM `users`
WHERE `email` = '' OR 1=1 --'
AND `password = 'user_password'
OOPS!
SQL injection
SELECT * FROM `users`
WHERE `email` = '' OR 1=1 --'
AND `password = 'user_password'
Since 1=1 is obviously true in any circumstances, and below
messages are commented out, this instruction will select all
users instead of logged in user.
Prepared statement
• By prepare query statement before execute,
we can prevent SQL injection
PREPARE SELECT * FROM `user` WHERE `id`=? AND `password`=?
OK, prepared
EXECUTE "enskylin", "nctu5566"
1 row in set (0.00 sec)
Password Hashing
• Let's look at User creation
INSERT INTO (id, password) VALUES ('ensky', 'nctu5566')
• Actually, it is very dangerous!
• Note that Database server is able to be cracked
If hackers can get your "real password", than it is a
big problem
• Even more, if database administrator can access your
real password, than it should be a problem, too.
more plaintext passwords:
https://www.facebook.com/PlainPass
How to solve the plaintext
password problem?
Password Hashing
Hashing!
a many-to-one no inverse function
http://www.php.net/manual/en/function.hash.php#104987
Password Hashed PW
hello 5d41402abc4 …
world 7d793037a07 …
Flow
• register
• login
• Reset
hello 5d41402abc4 … 5d41402abc4 …
generate hashed password save to database
hello 5d41402abc4 … 5d41402abc4 …
generate hashed password verify with database's hash
world 7d793037a07 … 7d793037a07 …
generate new hashed password save to database
Crack
• One common crack method is "rainbow table"
– detail algorithm: wiki
• password hashing can be cracked by using
predefined hash tables
• However it can be prevented by using "random salt"
for each password
Best practice
• Best practice to deal with hashing is to hash with
"random salt"
• Save
1. generate a random salt
2. hashing password use this random salt
3. save "hashed password" with random salt to database
• Verify
1. query hashed password with random salt by user
2. regenerate hashed password and verify with real data
PHP support
• PHP 5.5 supports password_hash, password_verify
functions to deal with password hashing problem
http://www.php.net/manual/en/function.password-hash.php
• However, CSCC only provides PHP 5.3
so you should use crypt function instead
http://www.php.net/manual/en/function.crypt.php
• Since crypt is not easy enough to use,
TA provided TA's version:
http://pastebin.com/aDdWvhXm
Usage
// create a hash
$hash = password_hash($_POST['password']);
// verify a hash
if (password_verify($_POST['password'], $hash))
{
echo 'Password is valid!';
} else {
echo 'Invalid password.';
}
References
• PDO: http://tw2.php.net/manual/en/class.pdo.php
• crypt: http://tw2.php.net/manual/en/function.crypt.php
• plainpassword: https://www.facebook.com/PlainPass
• pdo-mysql-mysqli:
http://blog.roga.tw/2010/06/%E6%B7%BA%E8%AB%87-php-mysql-php-
mysqli-pdo-%E7%9A%84%E5%B7%AE%E7%95%B0/

Mais conteúdo relacionado

Mais procurados

Cassandra for Python Developers
Cassandra for Python DevelopersCassandra for Python Developers
Cassandra for Python DevelopersTyler Hobbs
 
SunshinePHP 2017 - Making the most out of MySQL
SunshinePHP 2017 - Making the most out of MySQLSunshinePHP 2017 - Making the most out of MySQL
SunshinePHP 2017 - Making the most out of MySQLGabriela Ferrara
 
Security Bootcamp 2013 - Lap trinh web an toan
Security Bootcamp 2013 - Lap trinh web an toanSecurity Bootcamp 2013 - Lap trinh web an toan
Security Bootcamp 2013 - Lap trinh web an toanSecurity Bootcamp
 
Security Bootcamp 2013 lap trinh web an toan
Security Bootcamp 2013   lap trinh web an toanSecurity Bootcamp 2013   lap trinh web an toan
Security Bootcamp 2013 lap trinh web an toanSecurity Bootcamp
 
Scalable vector ember
Scalable vector emberScalable vector ember
Scalable vector emberMatthew Beale
 
Designing Opeation Oriented Web Applications / YAPC::Asia Tokyo 2011
Designing Opeation Oriented Web Applications / YAPC::Asia Tokyo 2011Designing Opeation Oriented Web Applications / YAPC::Asia Tokyo 2011
Designing Opeation Oriented Web Applications / YAPC::Asia Tokyo 2011Masahiro Nagano
 
Temporary Cache Assistance (Transients API): WordCamp Birmingham 2014
Temporary Cache Assistance (Transients API): WordCamp Birmingham 2014Temporary Cache Assistance (Transients API): WordCamp Birmingham 2014
Temporary Cache Assistance (Transients API): WordCamp Birmingham 2014Cliff Seal
 
Database madness with_mongoengine_and_sql_alchemy
Database madness with_mongoengine_and_sql_alchemyDatabase madness with_mongoengine_and_sql_alchemy
Database madness with_mongoengine_and_sql_alchemyJaime Buelta
 
jQuery%20on%20Rails%20Presentation
jQuery%20on%20Rails%20PresentationjQuery%20on%20Rails%20Presentation
jQuery%20on%20Rails%20Presentationguestcf600a
 
DPAPI AND DPAPI-NG: Decryption toolkit. Black Hat 2017
DPAPI AND DPAPI-NG: Decryption toolkit. Black Hat 2017DPAPI AND DPAPI-NG: Decryption toolkit. Black Hat 2017
DPAPI AND DPAPI-NG: Decryption toolkit. Black Hat 2017Paula Januszkiewicz
 
Caching and tuning fun for high scalability
Caching and tuning fun for high scalabilityCaching and tuning fun for high scalability
Caching and tuning fun for high scalabilityWim Godden
 
Introduction à CoffeeScript pour ParisRB
Introduction à CoffeeScript pour ParisRB Introduction à CoffeeScript pour ParisRB
Introduction à CoffeeScript pour ParisRB jhchabran
 
JWT - To authentication and beyond!
JWT - To authentication and beyond!JWT - To authentication and beyond!
JWT - To authentication and beyond!Luís Cobucci
 

Mais procurados (16)

Cassandra for Python Developers
Cassandra for Python DevelopersCassandra for Python Developers
Cassandra for Python Developers
 
SunshinePHP 2017 - Making the most out of MySQL
SunshinePHP 2017 - Making the most out of MySQLSunshinePHP 2017 - Making the most out of MySQL
SunshinePHP 2017 - Making the most out of MySQL
 
Security Bootcamp 2013 - Lap trinh web an toan
Security Bootcamp 2013 - Lap trinh web an toanSecurity Bootcamp 2013 - Lap trinh web an toan
Security Bootcamp 2013 - Lap trinh web an toan
 
Security Bootcamp 2013 lap trinh web an toan
Security Bootcamp 2013   lap trinh web an toanSecurity Bootcamp 2013   lap trinh web an toan
Security Bootcamp 2013 lap trinh web an toan
 
Scalable vector ember
Scalable vector emberScalable vector ember
Scalable vector ember
 
Cookies
CookiesCookies
Cookies
 
Designing Opeation Oriented Web Applications / YAPC::Asia Tokyo 2011
Designing Opeation Oriented Web Applications / YAPC::Asia Tokyo 2011Designing Opeation Oriented Web Applications / YAPC::Asia Tokyo 2011
Designing Opeation Oriented Web Applications / YAPC::Asia Tokyo 2011
 
Temporary Cache Assistance (Transients API): WordCamp Birmingham 2014
Temporary Cache Assistance (Transients API): WordCamp Birmingham 2014Temporary Cache Assistance (Transients API): WordCamp Birmingham 2014
Temporary Cache Assistance (Transients API): WordCamp Birmingham 2014
 
Database madness with_mongoengine_and_sql_alchemy
Database madness with_mongoengine_and_sql_alchemyDatabase madness with_mongoengine_and_sql_alchemy
Database madness with_mongoengine_and_sql_alchemy
 
jQuery%20on%20Rails%20Presentation
jQuery%20on%20Rails%20PresentationjQuery%20on%20Rails%20Presentation
jQuery%20on%20Rails%20Presentation
 
DPAPI AND DPAPI-NG: Decryption toolkit. Black Hat 2017
DPAPI AND DPAPI-NG: Decryption toolkit. Black Hat 2017DPAPI AND DPAPI-NG: Decryption toolkit. Black Hat 2017
DPAPI AND DPAPI-NG: Decryption toolkit. Black Hat 2017
 
Php mysq
Php mysqPhp mysq
Php mysq
 
Caching and tuning fun for high scalability
Caching and tuning fun for high scalabilityCaching and tuning fun for high scalability
Caching and tuning fun for high scalability
 
MongoDB With Style
MongoDB With StyleMongoDB With Style
MongoDB With Style
 
Introduction à CoffeeScript pour ParisRB
Introduction à CoffeeScript pour ParisRB Introduction à CoffeeScript pour ParisRB
Introduction à CoffeeScript pour ParisRB
 
JWT - To authentication and beyond!
JWT - To authentication and beyond!JWT - To authentication and beyond!
JWT - To authentication and beyond!
 

Destaque

Cross Site Request Forgery
Cross Site Request ForgeryCross Site Request Forgery
Cross Site Request ForgeryTony Bibbs
 
Momchil Kyurkchiev Presentation
Momchil Kyurkchiev PresentationMomchil Kyurkchiev Presentation
Momchil Kyurkchiev PresentationStart It Smart
 
Codeigniter : Two Step View - Concept Implementation
Codeigniter : Two Step View - Concept ImplementationCodeigniter : Two Step View - Concept Implementation
Codeigniter : Two Step View - Concept ImplementationAbdul Malik Ikhsan
 
Codeigniter
CodeigniterCodeigniter
Codeignitershadowk
 
CodeIgniter - PHP MVC Framework by silicongulf.com
CodeIgniter - PHP MVC Framework by silicongulf.comCodeIgniter - PHP MVC Framework by silicongulf.com
CodeIgniter - PHP MVC Framework by silicongulf.comChristopher Cubos
 
Codeigniter : the security and the magic of hook
Codeigniter : the security and the magic of hookCodeigniter : the security and the magic of hook
Codeigniter : the security and the magic of hookAbdul Malik Ikhsan
 
Modular PHP Development using CodeIgniter Bonfire
Modular PHP Development using CodeIgniter BonfireModular PHP Development using CodeIgniter Bonfire
Modular PHP Development using CodeIgniter BonfireJeff Fox
 
Zend Framework 2 : Dependency Injection
Zend Framework 2 : Dependency InjectionZend Framework 2 : Dependency Injection
Zend Framework 2 : Dependency InjectionAbdul Malik Ikhsan
 
CodeIgniter PHP MVC Framework
CodeIgniter PHP MVC FrameworkCodeIgniter PHP MVC Framework
CodeIgniter PHP MVC FrameworkBo-Yi Wu
 
Database design process
Database design processDatabase design process
Database design processTayyab Hameed
 
PHP Powerpoint -- Teach PHP with this
PHP Powerpoint -- Teach PHP with thisPHP Powerpoint -- Teach PHP with this
PHP Powerpoint -- Teach PHP with thisIan Macali
 

Destaque (17)

Cross Site Request Forgery
Cross Site Request ForgeryCross Site Request Forgery
Cross Site Request Forgery
 
Chapter2 j2ee
Chapter2 j2eeChapter2 j2ee
Chapter2 j2ee
 
Security in NodeJS applications
Security in NodeJS applicationsSecurity in NodeJS applications
Security in NodeJS applications
 
Momchil Kyurkchiev Presentation
Momchil Kyurkchiev PresentationMomchil Kyurkchiev Presentation
Momchil Kyurkchiev Presentation
 
Codeigniter : Two Step View - Concept Implementation
Codeigniter : Two Step View - Concept ImplementationCodeigniter : Two Step View - Concept Implementation
Codeigniter : Two Step View - Concept Implementation
 
DB design
DB designDB design
DB design
 
Codeigniter
CodeigniterCodeigniter
Codeigniter
 
CodeIgniter - PHP MVC Framework by silicongulf.com
CodeIgniter - PHP MVC Framework by silicongulf.comCodeIgniter - PHP MVC Framework by silicongulf.com
CodeIgniter - PHP MVC Framework by silicongulf.com
 
Week 3 database design
Week 3   database designWeek 3   database design
Week 3 database design
 
Codeigniter : the security and the magic of hook
Codeigniter : the security and the magic of hookCodeigniter : the security and the magic of hook
Codeigniter : the security and the magic of hook
 
Modular PHP Development using CodeIgniter Bonfire
Modular PHP Development using CodeIgniter BonfireModular PHP Development using CodeIgniter Bonfire
Modular PHP Development using CodeIgniter Bonfire
 
Zend Framework 2 : Dependency Injection
Zend Framework 2 : Dependency InjectionZend Framework 2 : Dependency Injection
Zend Framework 2 : Dependency Injection
 
CodeIgniter PHP MVC Framework
CodeIgniter PHP MVC FrameworkCodeIgniter PHP MVC Framework
CodeIgniter PHP MVC Framework
 
Database design process
Database design processDatabase design process
Database design process
 
PHP Project PPT
PHP Project PPTPHP Project PPT
PHP Project PPT
 
Php mysql ppt
Php mysql pptPhp mysql ppt
Php mysql ppt
 
PHP Powerpoint -- Teach PHP with this
PHP Powerpoint -- Teach PHP with thisPHP Powerpoint -- Teach PHP with this
PHP Powerpoint -- Teach PHP with this
 

Semelhante a 2014 database - course 3 - PHP and MySQL

My app is secure... I think
My app is secure... I thinkMy app is secure... I think
My app is secure... I thinkWim Godden
 
My app is secure... I think
My app is secure... I thinkMy app is secure... I think
My app is secure... I thinkWim Godden
 
SQL Injection 101 : It is not just about ' or '1'='1 - Pichaya Morimoto
SQL Injection 101 : It is not just about ' or '1'='1 - Pichaya MorimotoSQL Injection 101 : It is not just about ' or '1'='1 - Pichaya Morimoto
SQL Injection 101 : It is not just about ' or '1'='1 - Pichaya MorimotoPichaya Morimoto
 
My app is secure... I think
My app is secure... I thinkMy app is secure... I think
My app is secure... I thinkWim Godden
 
Web Security - Hands-on
Web Security - Hands-onWeb Security - Hands-on
Web Security - Hands-onAndrea Valenza
 
My app is secure... I think
My app is secure... I thinkMy app is secure... I think
My app is secure... I thinkWim Godden
 
My app is secure... I think
My app is secure... I thinkMy app is secure... I think
My app is secure... I thinkWim Godden
 
My app is secure... I think
My app is secure... I thinkMy app is secure... I think
My app is secure... I thinkWim Godden
 
My app is secure... I think
My app is secure... I thinkMy app is secure... I think
My app is secure... I thinkWim Godden
 
My app is secure... I think
My app is secure... I thinkMy app is secure... I think
My app is secure... I thinkWim Godden
 
Introduction to Active Record at MySQL Conference 2007
Introduction to Active Record at MySQL Conference 2007Introduction to Active Record at MySQL Conference 2007
Introduction to Active Record at MySQL Conference 2007Rabble .
 
High Performance Django
High Performance DjangoHigh Performance Django
High Performance DjangoDjangoCon2008
 
High Performance Django 1
High Performance Django 1High Performance Django 1
High Performance Django 1DjangoCon2008
 
Hacking Your Way To Better Security
Hacking Your Way To Better SecurityHacking Your Way To Better Security
Hacking Your Way To Better SecurityColin O'Dell
 
Introduction to Active Record - Silicon Valley Ruby Conference 2007
Introduction to Active Record - Silicon Valley Ruby Conference 2007Introduction to Active Record - Silicon Valley Ruby Conference 2007
Introduction to Active Record - Silicon Valley Ruby Conference 2007Rabble .
 
Service discovery and configuration provisioning
Service discovery and configuration provisioningService discovery and configuration provisioning
Service discovery and configuration provisioningSource Ministry
 
Hacking Your Way to Better Security - PHP South Africa 2016
Hacking Your Way to Better Security - PHP South Africa 2016Hacking Your Way to Better Security - PHP South Africa 2016
Hacking Your Way to Better Security - PHP South Africa 2016Colin O'Dell
 
Hacking Your Way To Better Security - Dutch PHP Conference 2016
Hacking Your Way To Better Security - Dutch PHP Conference 2016Hacking Your Way To Better Security - Dutch PHP Conference 2016
Hacking Your Way To Better Security - Dutch PHP Conference 2016Colin O'Dell
 

Semelhante a 2014 database - course 3 - PHP and MySQL (20)

My app is secure... I think
My app is secure... I thinkMy app is secure... I think
My app is secure... I think
 
My app is secure... I think
My app is secure... I thinkMy app is secure... I think
My app is secure... I think
 
SQL Injection 101 : It is not just about ' or '1'='1 - Pichaya Morimoto
SQL Injection 101 : It is not just about ' or '1'='1 - Pichaya MorimotoSQL Injection 101 : It is not just about ' or '1'='1 - Pichaya Morimoto
SQL Injection 101 : It is not just about ' or '1'='1 - Pichaya Morimoto
 
My app is secure... I think
My app is secure... I thinkMy app is secure... I think
My app is secure... I think
 
Web Security - Hands-on
Web Security - Hands-onWeb Security - Hands-on
Web Security - Hands-on
 
My app is secure... I think
My app is secure... I thinkMy app is secure... I think
My app is secure... I think
 
My app is secure... I think
My app is secure... I thinkMy app is secure... I think
My app is secure... I think
 
My app is secure... I think
My app is secure... I thinkMy app is secure... I think
My app is secure... I think
 
My app is secure... I think
My app is secure... I thinkMy app is secure... I think
My app is secure... I think
 
My app is secure... I think
My app is secure... I thinkMy app is secure... I think
My app is secure... I think
 
Php summary
Php summaryPhp summary
Php summary
 
Introduction to Active Record at MySQL Conference 2007
Introduction to Active Record at MySQL Conference 2007Introduction to Active Record at MySQL Conference 2007
Introduction to Active Record at MySQL Conference 2007
 
High Performance Django
High Performance DjangoHigh Performance Django
High Performance Django
 
High Performance Django 1
High Performance Django 1High Performance Django 1
High Performance Django 1
 
Hacking Your Way To Better Security
Hacking Your Way To Better SecurityHacking Your Way To Better Security
Hacking Your Way To Better Security
 
Introduction to Active Record - Silicon Valley Ruby Conference 2007
Introduction to Active Record - Silicon Valley Ruby Conference 2007Introduction to Active Record - Silicon Valley Ruby Conference 2007
Introduction to Active Record - Silicon Valley Ruby Conference 2007
 
Service discovery and configuration provisioning
Service discovery and configuration provisioningService discovery and configuration provisioning
Service discovery and configuration provisioning
 
Hacking Your Way to Better Security - PHP South Africa 2016
Hacking Your Way to Better Security - PHP South Africa 2016Hacking Your Way to Better Security - PHP South Africa 2016
Hacking Your Way to Better Security - PHP South Africa 2016
 
Hacking Your Way To Better Security - Dutch PHP Conference 2016
Hacking Your Way To Better Security - Dutch PHP Conference 2016Hacking Your Way To Better Security - Dutch PHP Conference 2016
Hacking Your Way To Better Security - Dutch PHP Conference 2016
 
php2.pptx
php2.pptxphp2.pptx
php2.pptx
 

Mais de Hung-yu Lin

2014 database - course 2 - php
2014 database - course 2 - php2014 database - course 2 - php
2014 database - course 2 - phpHung-yu Lin
 
2014 database - course 1 - www introduction
2014 database - course 1 - www introduction2014 database - course 1 - www introduction
2014 database - course 1 - www introductionHung-yu Lin
 
OpenWebSchool - 11 - CodeIgniter
OpenWebSchool - 11 - CodeIgniterOpenWebSchool - 11 - CodeIgniter
OpenWebSchool - 11 - CodeIgniterHung-yu Lin
 
OpenWebSchool - 06 - PHP + MySQL
OpenWebSchool - 06 - PHP + MySQLOpenWebSchool - 06 - PHP + MySQL
OpenWebSchool - 06 - PHP + MySQLHung-yu Lin
 
OpenWebSchool - 05 - MySQL
OpenWebSchool - 05 - MySQLOpenWebSchool - 05 - MySQL
OpenWebSchool - 05 - MySQLHung-yu Lin
 
OpenWebSchool - 02 - PHP Part I
OpenWebSchool - 02 - PHP Part IOpenWebSchool - 02 - PHP Part I
OpenWebSchool - 02 - PHP Part IHung-yu Lin
 
OpenWebSchool - 01 - WWW Intro
OpenWebSchool - 01 - WWW IntroOpenWebSchool - 01 - WWW Intro
OpenWebSchool - 01 - WWW IntroHung-yu Lin
 
OpenWebSchool - 03 - PHP Part II
OpenWebSchool - 03 - PHP Part IIOpenWebSchool - 03 - PHP Part II
OpenWebSchool - 03 - PHP Part IIHung-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 datasetsHung-yu Lin
 
Google App Engine
Google App EngineGoogle App Engine
Google App EngineHung-yu Lin
 

Mais de Hung-yu Lin (11)

2014 database - course 2 - php
2014 database - course 2 - php2014 database - course 2 - php
2014 database - course 2 - php
 
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

EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWERMadyBayot
 
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...DianaGray10
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024The Digital Insurer
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxRemote DBA Services
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Victor Rentea
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamUiPathCommunity
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Bhuvaneswari Subramani
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...Zilliz
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityWSO2
 
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.pptxRustici Software
 
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 businesspanagenda
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistandanishmna97
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfOrbitshub
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsNanddeep Nachan
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...apidays
 
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 TerraformAndrey Devyatkin
 
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, Adobeapidays
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Orbitshub
 

Último (20)

EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
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...
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
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
 
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
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
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
 
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
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 

2014 database - course 3 - PHP and MySQL

  • 1. PHP - MySQL Ensky / 林宏昱
  • 2. Load data from database GET /enskylin HTTP/1.1 Host: www.facebook.com HTTP/1.1 200 OK HTML
  • 3. generate HTML GET /enskylin HTTP/1.1 Host: www.facebook.com HTTP/1.1 200 OK HTML
  • 4. How to access database? • today's topic :D
  • 5. Establish a connection (you should set it up during your installation) (If you use cscc account, then follow the instruction on cscc MySQL website) username: root password: nctu5566 login successfully
  • 6. Do some Queries Insert: Create Select: Read Update: Update Delete: Delete INSERT INTO users (id, pw) VALUES ('jlhuang', 'iLove5566') Query OK, 1 rows affected
  • 7. Dealing with Results Generate the correspond HTML SELECT * FROM users 100 row in set (0.00 sec)
  • 9. Hello world! - connect Establish a connection: $db_host = "host_name"; $db_name = "database_name"; $db_user = "user_name"; $db_password = "password"; $dsn = "mysql:host=$db_host;dbname=$db_name"; $db = new PDO($dsn, $db_user, $db_password);
  • 10. Hello world! - Insert SQL -- INSERT INTO `users` (id, username, gender) VALUES(1, 'Ensky', 'male') PHP -- $sql = "INSERT INTO `users` (id, username, gender)" . " VALUES(?, ?, ?)"; $sth = $db->prepare($sql); $sth->execute(array(1, 'ensky', 'male')); id username gender 1 Ensky male
  • 11. Hello world! - Select $sql = "SELECT * FROM `users`" . " WHERE `username` = ? AND `password` = ?"; $sth = $db->prepare($sql); $sth->execute(array('ensky', 'nctu5566')); id username password gender 1 Ensky nctu5566 male 2 Emily sdfasdf female
  • 12. Hello world! - Retrieve $sql = "SELECT username, gender FROM `users`" . " WHERE `username` = ? AND `password` = ?"; $sth = $db->prepare($sql); $sth->execute(array('ensky', 'nctu5566')); while ($result = $sth->fetchObject()) { echo $result->name . $result->gender; } // Ensky male // Emily female // … id username password gender 1 Ensky nctu5566 male 2 Emily sdfasdf female
  • 13. Named parameters $sql = "SELECT username, gender FROM `users`" . " WHERE `username` = ? AND `password` = ?"; $sth = $db->prepare($sql); $sth->execute(array('ensky', 'nctu5566')); is equal to $sql = "SELECT username, gender FROM `users`" . " WHERE `username` = :un AND `password` = :pw"; $sth = $db->prepare($sql); $sth->execute(array( ':un' => 'ensky', ':pw' => 'nctu5566'));
  • 14. PHP Data Objects • PDO is an OO style class • Classes – PDO • PDO __construct ( string $dsn, [, string $username [, string $password ]]) • PDOStatement prepare( string $statement ) • PDOStatement query( string $statement ) – PDOStatement • bool execute ([ array $input_parameters ] ) • mixed fetchObject ([ string $class_name = "stdClass" [, array $ctor_args ]] )
  • 15. Don't use mysql_* • There are many libraries to help you connect to MySQL database – MySQL – MySQLi – PDO • If your books recommends you to use mysql_xxx functions, throws it.
  • 16. Don't use mysql_* • What's the problem of mysql_ functions? – It is deprecated in PHP 5.5.0, and will be removed in PHP6 – SQL Injection problem • no prepared statement – Only support MySQL(PDO supports 12 different databases)
  • 18. Simple query(use mysql ext) login_action.php -- <?php mysql_connect($db_host, $db_user, $db_password); mysql_select_db($dn_name); $result = mysql_query( "SELECT * FROM `users`" ." WHERE `email` = '{$_POST['email']}'" ." AND `password = '{$_POST['password']}'" ); // …
  • 19. Simple query(use mysql ext) login_form.php login_action.php -- $result = mysql_query( "SELECT * FROM `users`" ." WHERE `email` = '{$_POST['email']}'" ." AND `password = '{$_POST['password']}'" );
  • 20. Simple query(use mysql ext) login_form.php login_action.php -- $result = mysql_query( "SELECT * FROM `users`" ." WHERE `email` = 'enskylin@gmail.com'" ." AND `password = 'nctu5566'" );
  • 21. Simple query(use mysql ext) $result = mysql_query( "SELECT * FROM `users`" ." WHERE `email` = 'enskylin@gmail.com'" ." AND `password = 'nctu5566'" ); SELECT * FROM `users` WHERE `email` = 'enskylin@gmail.com' AND `password` = 'nctu5566'
  • 22. SQL injection "--" in SQL represents "comments" SELECT * FROM `users` -- I want to select all from user SELECT * FROM `users` -- today is a good day
  • 23. SQL injection If a cracker knows your query logic: SELECT * FROM `users` WHERE `email` = 'user_account' AND `password = 'user_password' give a try: user_account = ' OR 1=1 -- SELECT * FROM `users` WHERE `email` = '' OR 1=1 --' AND `password = 'user_password' OOPS!
  • 24. SQL injection SELECT * FROM `users` WHERE `email` = '' OR 1=1 --' AND `password = 'user_password' Since 1=1 is obviously true in any circumstances, and below messages are commented out, this instruction will select all users instead of logged in user.
  • 25. Prepared statement • By prepare query statement before execute, we can prevent SQL injection PREPARE SELECT * FROM `user` WHERE `id`=? AND `password`=? OK, prepared EXECUTE "enskylin", "nctu5566" 1 row in set (0.00 sec)
  • 26. Password Hashing • Let's look at User creation INSERT INTO (id, password) VALUES ('ensky', 'nctu5566') • Actually, it is very dangerous! • Note that Database server is able to be cracked If hackers can get your "real password", than it is a big problem • Even more, if database administrator can access your real password, than it should be a problem, too. more plaintext passwords: https://www.facebook.com/PlainPass
  • 27. How to solve the plaintext password problem? Password Hashing
  • 28. Hashing! a many-to-one no inverse function http://www.php.net/manual/en/function.hash.php#104987 Password Hashed PW hello 5d41402abc4 … world 7d793037a07 …
  • 29. Flow • register • login • Reset hello 5d41402abc4 … 5d41402abc4 … generate hashed password save to database hello 5d41402abc4 … 5d41402abc4 … generate hashed password verify with database's hash world 7d793037a07 … 7d793037a07 … generate new hashed password save to database
  • 30. Crack • One common crack method is "rainbow table" – detail algorithm: wiki • password hashing can be cracked by using predefined hash tables • However it can be prevented by using "random salt" for each password
  • 31. Best practice • Best practice to deal with hashing is to hash with "random salt" • Save 1. generate a random salt 2. hashing password use this random salt 3. save "hashed password" with random salt to database • Verify 1. query hashed password with random salt by user 2. regenerate hashed password and verify with real data
  • 32. PHP support • PHP 5.5 supports password_hash, password_verify functions to deal with password hashing problem http://www.php.net/manual/en/function.password-hash.php • However, CSCC only provides PHP 5.3 so you should use crypt function instead http://www.php.net/manual/en/function.crypt.php • Since crypt is not easy enough to use, TA provided TA's version: http://pastebin.com/aDdWvhXm
  • 33. Usage // create a hash $hash = password_hash($_POST['password']); // verify a hash if (password_verify($_POST['password'], $hash)) { echo 'Password is valid!'; } else { echo 'Invalid password.'; }
  • 34. References • PDO: http://tw2.php.net/manual/en/class.pdo.php • crypt: http://tw2.php.net/manual/en/function.crypt.php • plainpassword: https://www.facebook.com/PlainPass • pdo-mysql-mysqli: http://blog.roga.tw/2010/06/%E6%B7%BA%E8%AB%87-php-mysql-php- mysqli-pdo-%E7%9A%84%E5%B7%AE%E7%95%B0/