0% found this document useful (0 votes)
24 views

Web Chapter 6

Uploaded by

Nati
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views

Web Chapter 6

Uploaded by

Nati
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 54

CHAPTER

SIX
Database Driven
Websites
 PHP/MySQL
 Understanding the MySQL Privilege
System

Locking and concurrency
 Speeding up database wit indexe
queries h s

General optimization tips

Different table types

Loading data from a file
 Making your database secur
more e
 Web security and cryptography
theory
 Static Web pages
 Data is stored in .html
files
changes their
 Won't change until source
someone codes
 Dynamic Web
pages
 Web pages that respond to users' requests
and gather
information from them. Oftentimes, they
have built-in
links to a database, from which they extract
 data based
on input from the users
 A database-driven Web site is a Web site that
uses a
database to gather, display, or manipulate
 information
 News sites: CNN.com and MSNBC.com
Example:
 E-commerce companies: Amazon.com, which
is a Web interface of a big-sized database
system containing customer and
transactional
 What do we needinformation.
to built a database-driven
website?
 A DBMS & a scripting
language
 Commercial databases: Oracle, SQL
Server
Cost:
 expensive
 Hardware requirements:
high
 Have an impressive array of advanced
features
 Open source databases: PostgreS
MySQL, QL
Cost:
 cheap
 Hardware
requirements: low
 Lack some advanced
features
 Open- scriptin languag
source g es
PH
P
 JS
P
 Per
l
 Proprieta scripting
ry languages

ASP
Cold
.NET
Fusion
 MySQL is the de-facto standard database
system for
web sites with HUGE volumes of both
data and
end-users (like Facebook, Twitter, and
Wikipedia).

 PHP combined with MySQL are cross-


platform
(you can develop in Windows and serve on
a Unix
platfor
m)
 MySQ is ideal for both small and large
L applications

MySQ is very fast, reliable, and easy
 L to use
 MySQ uses standard SQL
 L
compiles on a number of platforms
 MySQ is developed, distributed, and by
L is free to download and use
supported
Oracle Corporation
MySQ
 L
MySQL is named after co-founder Monty
Widenius's
MySQ
daughter: My
L
 PHP5 and later can work with a
MySQL
database using:
MySQLi extension (the "i" improve
 stands for d)
 only work with MySQL databases
 supports both procedural and OO
PHP
 PDO (PHP Data Objects)
 will work on 12 different database
systems
 Supports only OO
PHP
 Connecting to MySQL server
via PHP
$co = mysqli_connect(servernam
n e,
username password)
, ;
 $con is a connection resource type. We use this variable
to refer to
the connection created

 To select a specific database

mysqli_select_db(database_name
,$c on);
<?php
$servername = "localhost"; $username = "username";
$password = "password";
// Create connection
$conn = mysqli_connect($servername, $username,
$password);
// Check connection
if (!$conn) {
die("Connection failed: " .
mysqli_connect_error());}
?> else echo "Connected successfully";
Equivalent to
<?
php
$conn = mysqli_connect("localhost","username", "password") or
die("Connection failed: " . mysqli_connect_error());
echo "Connected successfully";
?>
 PHP function for making
queries:
mysqli_query(query_strin con_resource)
g, ;
 Queries that return information, such as
SELECT:
returns a result set
$resul = mysqli_query(query_strin$con)
t g, ;
 In this case, the result set is stored in the
variable $result
 Other queries, returns TRUE upon success
and FALSE
on failure. Best practice is to handle the error
(e.g.
die(mysql_error()))
 CREATE DATABASE dbname
 CREATE TABLE table_name (column_name
data_type(size), column_name data_type(size) …)
 INSER INTO table_name (column1, column3,...
T column2, )
VALUE (value1, value2, value3,...)
 S
column1, column2 …
FROM table_name
SELEC
T
WHERE some_column=some_value
 UPDATE table_name
SET column1=value,
column2=value2,...
WHERE some_column=some_value

DELETE FROM table_name
WHERE some_column = some_value
 Rules to follow while making query
strings
The SQL query must be
 quoted
 String values inside the SQL b
query must e
quoted
 Numeric values must not be
quoted
 The word NULL must not be
quoted
<?php
// Create connection
$conn = mysqli_connect("localhost", "username",
"password")
or die("Connection failed: ". mysqli_connect_error());
// Create database
$sql = "CREATE DATABASE myDB";
if (mysqli_query($conn, $sql)) {
echo "Database created successfully";
}else{
echo "Error creating database".
mysqli_error($conn);
}
mysqli_close($conn
?> );
<?php
// Create connection
$conn = mysqli_connect("localhost","username", ”mydb” or
"password“, )
die("Connection failed: ". mysqli_connect_error());
// sql to create table
$sql = "CREATE TABLE MyGuests (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date
TIMESTAMP)";
if (mysqli_query($conn, $sql)) {
echo "Table MyGuests created successfully";
} else {
echo "Error creating table: " .
mysqli_error($conn);
}
mysqli_close($conn);
?>
<?php
$servername = "localhost"; $username =
"username";
$password = $dbname =
"password"; "myDB";
// Create
$conn = connection
mysqli_connect($servername, $username, $dbname)
$password, or
die("Connection failed: ".
mysqli_connect_error());

$sql = "INSERT INTO MyGuests (firstname, email


lastname, )
VALUES ('John', 'Doe', '[email protected]
')";
mysqli_query($conn, $sql)) or die("Error: “ .
mysqli_error($conn));

echo "New record created


successfully";
mysqli_close($conn);
?>
<?php
$servername = "localhost"; $username =
"username";
$password = $dbname =
"password"; "myDB“;
// Create
connection
$conn = mysqli_connect($servername, $username, $dbname or
$password, )
die("Connection failed: ".
mysqli_connect_error());
// Create
Query
$sql ="UPDATE MyGuests lastname='Doe WHERE
SET ' id=2";
// Execute
Query
mysqli_query($conn, or “ .
$sql)) die("Error: mysqli_error($conn));
echo “Record
updated";
mysqli_close($conn
);
<?php
$servername = "localhost"; $username =
"username";
$password = $dbname =
"password"; "myDB“;
// Create
connection
$conn = mysqli_connect($servername, $username, $dbname or
$password, )
die("Connection failed: ".
mysqli_connect_error());
// Create
Query
$sql ="DELETE FROM MyGuests WHERE
id=3";
// Execute
Query
mysqli_query($conn, $sql)) or “ .
die("Error: mysqli_error($conn));
echo “Record
Deleted";
mysqli_close($conn
);
 The PHP function num_rows() is used to check if
there are
more than zero rows returned
 The function fetch_assoc() puts all the into
results an
associative array that we can loop
 through

Example
if (mysqli_num_rows($result)
$result = mysqli_query(query,>
0) {
$con);
while ($row mysqli_fetch_assoc($result {
= ))
$col =
1 $row['column_1_name'];
=
$col $row['column_2_name'];
2 so
forth...
} //
and
}
<?php
$servername = "localhost"; $username =
"username";
$password = $dbname =
"password"; "myDB";
$conn = mysqli_connect($servername, $username, $password,
$dbname) or
die("Connection failed: ".
mysqli_connect_error());
$sql = "SELECT id, fname, lname FROM
MyGuests";
mysqli_query($conn, $sql)) or die("Error: “ .
mysqli_error($conn));
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
echo "id:". $row["id"]. "Name:". “.
$row[“fname"].” $row["lname"]."<br>";
}
} else {
echo "0 results";}
mysqli_close($conn);
 A prepared statement is a feature used to execute
the same (or
similar) SQL statements repeatedly with high
 efficiency.
Prepared statements basically work
like this:
 Prepare: An SQL statement template is created and sent to
the database.
Certain values are left unspecified, called parameters
(labeled "?").
 Example: INSERT INTO MyGuests VALUES(?, ?, ?)
 The database parses, compiles, and performs query
optimization on the
SQL statement template, and stores the result without
executing it
 Execute: At a later time, the application binds the values to
the
parameters, and the database executes the statement. The
application
may execute the statement as many times as it wants with
different values
 Compared to executing SQL statements directly,
prepared
statements have two main advantages:
 Prepared statements reduces parsing time as the
preparation on
the query is done only once (although the statement is
executed
 multiple times)

Bound parameters minimize bandwidth to the server


 as you need
to send only the parameters each time, and not the
whole query
Prepared statements are very useful against SQL
injections,
because parameter values, which are transmitted later
using a
 The LOAD DATA INFILE
statement
 Is used to load table data in fil
from a e
 It executes very
quickly
 Synta
x:
 LOAD DATA INFILE INTO
filename TABLE
tablename;
 By default, data fields in the file must be
separated
by tabs and enclosed in single quotation
marks, and
 In Database-Driven Websites or web
based
applications speed is a big issue
 Ther are a lot of techniques that
e you can
speed executio of querie Som
use up n s. e
to
 Using
are:
Indexes
 Optimization
Techniques
 A database index is a data structure that improves the
speed of data
retrieval operations on a database table at the cost of
additional writes

and storage space to maintain the index data structure.
 ALTER TABLE table ADD INDEX
The(column);
SQL to add an index to column of a table is
 Indexes are best used on columns that are frequently
used in where
clauses, and in any kind of sorting, such as "order by".

you can check which indexes are being used by running
 EXPLAIN
 don't create indexes that are not being used by your
queries
 Indexes slow down inserts and updates, so use them
carefully on
columns that are FREQUENTLY updated.
 Design
Optimization
 Everything (data & data types) in a database should be
as small as
possibl
 e
 Minimize
 redundancy
 Minimize
nulls
Make your primary key as short as
 possible

Avoid variable length columns if


possible (varchar, text and blob).
Fixed-length fields are faster but
might take up a little more space
 Table
Optimization
 If a table has been in use for a period of time, data
can become
fragmented as updates and deletions are process
 This fragmentation increases the time taken to find things
in this table
 This problem can be fixed by using the
statement
 OPTIMIZE TABLE tablename; or

 myisamchk -r tablename at the command


 Simplify
prompt
permissions
 Queries are checked against the permission system
before being
executed
 The simpler the permission process is the faster your
query will run
 Database-Driven Web ar ful
Applications e l
of concurrent database
 operations
So the question is
 How can we manage concurrent to
access
records, tables & databases?
 Solutions
 Using Concurrency Control
Mechanisms
 Concurrency control and locking
mechanism
 is used by DBMSs for the sharing of data
 the primary use of locking is to solve
concurrency
problems
 is
is necessary to ensure data consistency a
possibility of multiple clients possibl
when thereand
accessing y
modifying the same data at the same
 Locking
time. Types:
 table-level
locks &
 row-level locks.
 Table-level
locks
 locks the entire table while performing operations on
the table

allows only one session to update a table at a time

other sessions that want to modify the table must
wait until the
 current DML statement finishes
 deadlocks can be fairly easily avoided

has poor performance in applications that do a large


 number of
 concurrent reads and writes
suitable for read-only, read-mostly, or single-user
applications
 Row-level
locks
 possible to lock a single row while other sessions are
still able to
access the rest of the table

simultaneous write access by multiple sessions

allow high performance at a very high level of
concurrency at the
 cost of greater complexity in the implementation

slower performance for applications that have a low


 probability of
 lock contention as well as higher probability of bugs.
 very difficult to completely avoid deadlocks
MySQL uses row-level locking for InnoDB tables
suitable for multi-user, highly concurrent
 Types of
locks
 Read
lock
 The session that holds the lock can read the table (but
not write it).

Multiple sessions can acquire a READ lock for the table
at the same
 time.

 Write
Other sessions are not allowed to acquire a WRITE lock
lock
 The session that holds the lock can read and write to
the table

Only the session that holds the lock can access the
table. No other
 session can access it until the lock is released

Lock requests for the table by other sessions is blocked


 SQL to lock a table
LOCK TABLES table_name
lock-type;
-- execute queries here
UNLOCK TABLES;
 lock-type is either READ OR
 Example WRITE

mysqli_query($db, "LOCK mytes WRITE;"


TABLES t );
for mysqli_query($db,
($i = 1; $i < 100000; ++$i)
"INSERT INTO mytest VALUES ($i,
{ $i, $i);"); }
mysqli_query($db, "UNLOCK
TABLES;");
 Storage Engine (Table
Type)
 is what stores, handles, and retrieves information
from a table.
 The standard engines supported by
MySQL are:
 MyISAM
 The common storage
 InnoDB engines
MyISAM and
 MERGE  InnoDB
 The default storage
 MEMORY engine
(HEAP) MyISA
  M
BDB  You can also assign a storage engine to a
 specific
(BerkeleyDB)
table with the following
 syntax:
EXAMPLE
CREATE TABLE tblname(col1,
  col2, ..)
ARCHIVE
ENGINE =

CSV storageEngine;
 All storage engines can be selected per

BLACKHOL server, per
E
 MyISA
M
 Is the default storage engine for MySQL servers.
 Is a branch, or child, of the ISAM engine.
 Doesn’t support transaction,
 Supports table-level locking as opposed to row-level locking,
 Has the best performance and functionality
 is great for sites that have a very low INSERT/UPDATE
rate and a very
high SELECT rate.

Do not support foreign keys

The max number of rows supported for MyISAM is
~4.29E+09 with up to
64 indexes per table. Fields of TEXT/BLOB can be fully
indexed for cases
such as searching.
 InnoD
B
 compared to MyISAM, InnoDB provides many more
feature to
increase performance.

supports row-level locking, as opposed to table-level
locking
 This allows parallel INSERT/UPDATE/DELETE queries to be
 provides
run on theforeign key functionality.
same table, unlike MyISAM where each query has to wait its
 supports Transactions
turn to run.
 provides caching for data and indexes in memory,
as well as on
disk, which provides a large increase in performance
gain. For
those low on RAM this might not be the ideal
solution.
 MERG
E
 Allows users to treat collection of identical
MyISAM
tables as a single table for the purpose of
 There are constraints to this type, such as
querying.
all tables
needs to have the same definition.
 Example Scenario
 If you store sales transactions on your site in a daily
table, and
want to pull a report for the month, this would allow
you to
execute a query against a single table to pull all sales
for the
 MEMORY
(HEAP)
 Tables of this type are stored in memory and their
indexes are
hashed

Makes memory tables extremely fast, but, in the
event of a crash,
 your data will be lost

Ideal for storing temporary or derived data
 BDBDoesn’t support BLOB, TEXT, or AUTO INCREMENT
(BerkeleyDB)
columns
 Supports transactions and uses a hash based
storage system
 This allows for some of the quickest reading of data,
especially when
 Thepaired
biggest
withdownfall of the BDB system, is speed on
unique keys.
un-index
 The MySQL
server
stores privilege information in the grant
 tables
(user, host, db, tables_priv &
columns_priv) of the
mysql database (that is, in the database
named
 reads the contents of these tables into
memory
mysql)
when it starts and bases access-control
decisions
on the in-memory copies of the grant
 user
table
 determines whether a user can connect to a MySQL server
and

whether a user has any global privileges that apply to
every database in the server
 host table
 determines which host(s) can connect to the
MySQL server

db table
 determines which user can access which database from
which host
 tables_pr
iv
 determines which user can access which tables from
which database
 columns_pr
iv
 determines which user can access which columns
within a table
 MySQL Access
Control
 MySQL uses the grant tables to determine
what a
user is allowed to do in a two stage process
1
. Connection Verification
 The MySQL server checks if a user is allowed to
connect, based on the information from the user
2 Request Verification
. and host table
 After a connection is established, the server
checks each
statement you issue to determine whether you
have
 The MySQL server reads the grant tables
when it is
started

When you update the grant tables using
grant and tha
t
revoke statements the MySQL server will
 not notice
To point out to that a change has
server
they have changedoccurred, you
can run the commands
 flush
following
privileges //from mysql command line
 mysqladmin flush-privileges //from the
operating system
 mysqladmin //from the operating
reload system
1 Running MySQL server as
. a root
 is a bad idea if you are running a Unix-Like OS
 doing this gives a MySQL user with a full set of privileges. The
right to read and
write files anywhere in the operating system

Instead setup a MySQL user specifically for the purpose of
2 Setup themysqld
running MySQL server behind firewall, to stop
. connection from
unauthorized machines
 The default port to connect to the mysql
server is 3306
3 Make sure that all your users have passwords and that they
. are well
chosen and regularly changed, as with operating system
4. passwords Write
you PHP scripts that are used to connect to the database in a
separate file
called dbconnect.php, that you then include when required .
 Don’t store passwords in plain text in your database
 You can encrypt passwords using MySQL SHA1(). When you
run select you
will need to use the same function again to check the password
a user has

typed

Don’t grant more privileges to any user than he/she needs .

Don’t grant the PROCESS, FILE, SHUTDOWN and RELOAD


 The PROCESS privileges can be used to see what other users are doing
privileges to any user other than an administrator
and typing,
including their passwords

The FILE privilege can be used to read and write files to and from the
 Grant users system
operating access only from the hosts that they will be
connecting from like
jane@localhost

You can further increase security by using IP addresses rather
than domain
names in your host table
 Secure Hash
Algorithm
 String sha1(String str [, bool
raw_output])
 Returns pseudo random 40-character
 Ifstring
raw_output is set
true
 It returns random 20-character string of
binary data

The password cannot be decrypted back

If(sha1($password)==lajsdf0asdfj323j8258
 Example
hasdf93q)
 Select count(*) from authorized_users where
name=$username
and password=sha1($password)
 The password column should have
varchar(40)
 Connecting MySQL database to the web raises special
security issues

Set up a special user just for the purpose of web
 connections

Give the minimum privilege necessary and not grant DROP,


 ALTER
and CREATE privileges to that user
 Unless you are using SSL users password will be
transmitted from the
browser to the server in plain text
 Addslashes(), stripslashes() to get rid of any problematic
Do characters
a general in
data clean up before sending anything to the
MySQL
strings

database
Doubleval() to check that the numeric data is really
numeric
 SQL injection is a technique where
malicious users can inject SQL
commands
into an SQL statement, via web
page input.
 Injected SQL commands can alter
SQL
statement and compromise the
security of a
web application.
 SQL Injection Based on 1=1 is Always
True
 txtSQL = "SELECT * FROM Users WHERE UserId = " + userinput
 Let's say that the original purpose of the above
code was to
create an SQL statement to select a user with a
 given user id.

If there is nothing to prevent a user from entering


"wrong"
input, the user can enter some "smart" input like
this:
 Server Result
 SELECT * FROM Users WHERE UserId = 105 or 1=1
 this will return all rows from the table Users, since
WHERE 1=1 is always true.
 SQL Injection Based on Batched SQL
Statements
 Most databases support batched SQL statement, separated by
semicolon.

Example
 txtSQL = "SELECT * FROM Users WHERE UserId = " + userinput
 User inputs the
following

 Result
 The code at the server would create a valid SQL statement
like this:
 SELECT * FROM Users WHERE UserId = 105; DROP
 Solution
TABLEto SQL
Suppliers
injection
1 Do input screening before sending user input to a
. database
2 Use prepared statements than normal statements
.
 Use addslashes() to filter data before it is passed to
a database
 escapes out characters that might be troublesome to
a database

you can use the stripslashes() function to return the
data to its
 Switch on form
original magic_quotes_gpc and
magic_quotes_runtime
directives in php.ini
 automatically adds and strip slashes for incoming GET,
POST and
COOKIE variables to and from databases
 Use the escapeshellcmd() when passing user data to
a system()
or exec() call
 escapes out any meta-characters that can be used to
force the
system to run arbitrary commands entered by a
 The strip_tags() strips out HTML and
PHP tags
from a string
 prevents users from planting a in use
malicious script r
data
 htmlspecialchars() PHP function converts
characters to HTML entities
 for example, < is converted to &lt; this function
converts any
script tags to harmless characters
 trim() strips unnecessary characters
(extra space,
tab, newline) from the user input data
<?php
$name = $email = $gender = $comment =
if ($_SERVER["REQUEST_METHOD"]
$website = ""; == {
"POST")
$name = test_input($_POST["name"]);
$email = test_input($_POST["email"]);
$website =
test_input($_POST["website"]);
$gender = test_input($_POST["gender"]);
}
function
test_input($data) {
$dat =trim($data);
a =stripslashes($data);
$dat =htmlspecialchars($d
a
return ata);
}$data;
$dat
?a

You might also like