SQL and general input safety

This post was written by Brandon on April 21, 2009
Posted Under: PHP

If your website is taking data from the user in anyway, whether it be a search bar, a login form, or register form, without proper safety measures you can suffer an SQL injection attack. SQL injection will basically let the end user run queries on your database, meaning they will be able to read data, or even drop the whole thing. Other attacks that can happen is XSS, or Cross Site Scripting. This is when the user gets another script hosted elsewhere to run on your server, without even needing access to your server root itself.

Here are some simple things you can do to prevent these attacks:

1. Use htmlentities($string) - Mainly to prevent XSS
This converts HTML to raw text, so if your taking data from the user that is later displayed on the screen, they cant run java script or send other html through.

Usage example:

 $searchquery = htmlentities($searchquery);

Use stripslashes($string) - Removes all the backslashes in escaped characters, cleans up the data for sql queries

Usage example:

 $searchquery = stripslashes($searchquery);</code>
 
Use mysql_real_escape_string($string) - Escapes special characters: <strong>Requires a mysql connection to work!</strong>
 
Usage Example: 
<pre lang="php"> $searchquery = mysql_real_escape_string($searchquery);

In all my scripts that take data from the user, I call each of these one after another for every piece of data coming in.
I hope these are helpful and will be used to keep your web server safe!

Reader Comments

Trackbacks

Add a Comment

required, use real name
required, will not be published
optional, your blog address

Next Post: