SlideShare a Scribd company logo
1 of 34
Download to read 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/

More Related Content

What's hot

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
 

What's hot (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!
 

Viewers also liked

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
 

Viewers also liked (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
 

Similar to PHP MySQL - Access Database, Prevent SQL Injection & Secure Passwords

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 1
High Performance Django 1High Performance Django 1
High Performance Django 1DjangoCon2008
 
High Performance Django
High Performance DjangoHigh Performance Django
High Performance DjangoDjangoCon2008
 
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
 

Similar to PHP MySQL - Access Database, Prevent SQL Injection & Secure Passwords (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 1
High Performance Django 1High Performance Django 1
High Performance Django 1
 
High Performance Django
High Performance DjangoHigh Performance Django
High Performance Django
 
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
 

More from 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
 

More from 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
 

Recently uploaded

SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxBkGupta21
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfPrecisely
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 

Recently uploaded (20)

SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptx
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 

PHP MySQL - Access Database, Prevent SQL Injection & Secure Passwords

  • 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/