Datasheet
This is because the URL is now /buzzwatch/watch.php?name=jw-a. What has been added after the
question mark is called a query string. It contains parameters that are available in PHP scripts in the
$_GET global variable. The function readOne is similar to what you’ve already seen with a single highly
critical point to note:
function readOne() {
$db=openDb();
$query = $db->query(
“SELECT * from watches where symbol=’”.
sqlite_escape_string(trim($_GET[‘name’])).”’”
, SQLITE_ASSOC);
if ($row = $query->fetch(SQLITE_ASSOC)) {
displayOne($row);
} else {
$xml = simplexml_load_string(“<watch/>”);
$asXML = $xml->asXML();
print substr($asXML, strpos($asXML, ‘<’, 2));
}
}
Basically, the function selects a single row from the database and returns it as XML using the same
displayOne function that you’ve already seen.
Have you found what is really critical in this function? The small detail that makes a difference between
a function that hackers can easily exploit to delete your complete database and a function which is
secure? As any web application powered by a SQL database, BuzzWatch is potentially vulnerable to the
kind of attacks known as SQL injection. Instead of
name=jw-a, a hacker could send the request:
name=jw-a’;%20delete%20from%20watches;select%20*%20from%20watch%20where%20
symbol=’jw-a
That’s a very easy attack; the hacker would just have to type the URL in a browser. For this request, the
value of
$_GET[‘name’] is
jw-a’; delete from watches;select * from watch where symbol=’jw-a
and if you use this value to create your SQL select without calling the sqlite_escape_string() func-
tion, you get the following request:
select * from watches where symbol=’ jw-a’; delete from watches;select *
from watch where symbol=’jw-a’
SQLite, like most SQL databases, uses the semicolon (;) as a separator between queries and executes on
one but three queries and one of them,
delete from watches, deletes all the data in your table.
You learn more about security in Chapter 18, but you should remember that the Internet is a jungle and
that security should be on your mind at all times when building a web application. SQL injection is a
good example of simple attacks that are easy to counter (escaping parameter values as you’ve seen here
is a simple way to make sure that these values will be interpreted as single strings by the SQL database
and won’t leak out of the string into other SQL statements). Unfortunately, new web applications are
rolled out every day that are vulnerable to SQL injection because their developers were not aware of
this attack.
18
Chapter 1
04_087889 ch01.qxp 5/2/07 12:56 PM Page 18