Chris Nizzardini, Salt Lake City Utah, Web Developer Specializing in LAMP+Ajax Since 2006

My Blog

Here is my awesome blog.

Type Casting In PHP To Prevent XSS and SQL Injection

Lots of developers think the best way to prevent XSS and SQL injection attacks are by passing all user input through a filter function. If you’re one of these developers don’t worry, you’re still right. There is a better (less code and less CPU cycles) way to do this on certain user inputs though. Type casting to integers should be used on all user inputs that should be a numeric value. This ensures that a valid data type is being used and it automatically converts any strings to an integer. This effectively prevents any SQL injection or XSS attacks.

1
$customer_id = (int) $_POST['customer_id'];

This automatically prevents someone from being able to pass in something like:

1
1' OR 1='1

or

1
window.location 'aol.evilcloneofaol.com'

Tags: , , ,

One Response to “Type Casting In PHP To Prevent XSS and SQL Injection”

Leave a Reply