Categories Security

Protecting Against SQL injection and XSS in php using the PDO library

SQL injection and XSS(Cross Site Scripting) are two of the most deadly vulnerability that could be found in any web application. But it mostly happens due to developers mistake. When it comes to connecting to database many of us are familiar with mysql and mysqli. But from PHP 5.1 version and onward there is a better way. PHP DATA OBJECT or PDO. It helps developer by making it very easy to work with prepared statements.

Protectiong from SQL injection

Using PDO properly we can protect against SQL injection attacks. And it is recommended that new developers follow this method.

<?php 
$handle = $db->prepare( 'SELECT * FROM users WHERE username=(:user) AND password=(:pass) LIMIT 1;' );
$handle->bindParam( ':user', $user, PDO::PARAM_STR );
$handle->bindParam( ':pass', $pass, PDO::PARAM_STR );
$handle->execute();
$row = $handle->fetch();

// Make sure only 1 result is returned
if( $handle->rowCount() == 1 ) {
// Get values
$first = $row[ 'username' ];
$last = $row[ 'password' ];
?>

Notice the extra first bracket surrounding the dynamic parameter. You can also do this to insert and update queries. This is not a PDO tutorial ofcourse. You can learn about it from various tutorials.

Protection Against XSS
Although the query above will protect against SQL injection PDO prepared queries will NOT save from xss attacks if unchecked. When if you are saving data to the database and show them without filtering. It will create a stored XSS vulnerability. Even if there is no database showing unfiltered data can cause XSS. As the example below will demonstrate.

<?php 
    $text = $_GET['text']; 
    echo $text; ?>

Now if we enter any html or javascript code in the text parameter through get request for example like below

xssvuln.php?text=<script>alert('xss')</script>

So how do we stop that? We use a simple function in php called htmlspecialchars().

Now the code becomes

<?php 
    $text = $_GET['text'];
    echo htmlspecialchars($text); ?>

This function translates special characters to safe non executable codes. You can learn more about it from the php official website.

Hope you like the tutorial. Leave your suggestion for improvement in the comment box below.

About the author

Leave a Reply

Your email address will not be published. Required fields are marked *