Learning PHP and MySQL

Cross-Site Scripting Attacks

To guard against these attacks, you should pass any strings that came from a user through the htmlentities function. It takes the format:

htmlentities(string_to_clean)

For example:

print  "The title of the book is: " 
htmlentities($_POST['title']);

Here’s an example of what htmlentities does to the string:

<?php
$sample  
=  "A  sample  is  <i>italics</i>";
echo  
htmlentities($sample);
?>

When executed, this returns:

A sample is <i>italics</i>

Here’s a script to display the title table with the htmlentities functionality added:

<?php require_once('db_login.php'); require_once('DB.php');
$connection  =  DB::connect("mysql://$db_username:$db_password@$db_host/$db_database");
if  (
DB::isError($connection)){
die  ("Could  not  connect  to  the  database:  <br  />".  DB::errorMessage($connection));
}
//  Dislplay  the  table
$query  =  "SELECT  *  FROM  `books`";
$result  =  $connection->query($query);
if  (
DB::isError($result)){
die("Could  not  query  the  database:  <br  />".$query."  ".DB::errorMessage($result));
}
echo  '<table  border="1">';
echo  
"<tr><th>Title</th><th>Pages</th></tr>";
while  (
$result_row  =  $result->fetchRow(DB_FETCHMODE_ASSOC))  {
echo  "<tr><td>";
echo  
htmlentities($result_row["title"])  .  '</td><td>';
echo  
htmlentities($result_row["pages"])  .  '</td></tr>';
}
echo  "</table>";
$connection->disconnect();
?>

Posted by on 09/25 at 11:11 AM

Next entry: Example 12-8 Updating a field

Previous entry: Example 12-7 Checking for magic quotes

<< Back to main