Secure GET with intval

by admin on juli 26, 2011

A big problem, and a rather common one, is that users try to modify (read: hack) a websites to do things that the code wasen’t supposed to. Such as allow a basic user – to gain admin-access. This can easily be done by changing the data posted by $_GET.

So – how can we prevent this?
By using php’s function called intval() we can check that it returns as an integer.

This is how it can be done:

// Echo out the user-id wich we get from $_GET wich will return 1 or 1=1
echo $_GET['userId'];
// Wrap the $_GET with intval()-function and set it to the $id variable
$id=intval($_GET['userId']);
// Echoing out the id will now return '1'
echo $id; // 1

// We're now selecting som the table "users" with out '$id' var - wich is a clean integer variable! This is safe!
mysql_query('SELECT * FROM users WHERE id='.$id);

Do remember to sanitize your variables with more functions if they contain other data than just integers. Using stripslashes and mysql_real_escape_string is a good method! More on this in a later post!

Leave your comment

You must be logged in to post a comment.