View Full Version : SQL injection

01-09-2008, 10:36 PM
Hi everybody
I want to write a function to protect me from sql injection, so I can call it in every $_GET .
my $_GET is always an integer number ,I started with this function :
function valid_id($id){
if (preg_match ("/^([0-9]+)$/", $id)){

return $id;
} else {
return '0';

But the problem is it doesnt scape single quotes and if I insert a word it shows normally, I want the function to remove any letter and prevent any sql injection
can anybody help me out to write this function??

01-10-2008, 12:14 AM
mysql_real_escape_string, htmlspecialchars and intval all return a value, they don't change the variable you pass to it, so you'll need to assign the result of calling it to something - you may as well keep using $id:

function valid_id($id) {
if (preg_match ("/^([0-9]+)$/", $id)){
$id = intval($id);
$id = mysql_real_escape_string($id);
return $id;
} else {
return '0';

You'll notice also that I took out the htmlspecialchars call, there's no need to run this on data going in to the database, it's intended for use on data being displayed as HTML.

01-10-2008, 12:29 AM
just curious...isn't the mysql_real_escape_string call redundant if intval already returns an integer?

01-10-2008, 12:41 AM
aha, thank you
as I can see from you is the htmlspecialchars used when retriving data from mysql, is that right ?
but is that enough to prevent entering an appropriate data to the database?

01-10-2008, 01:48 AM
It looks as though you are only casting all-numeric strings as integers. If there are any non-numeric characters, then you return 0 as a string. Here is a simplified solution for you:

function valid_id( $id )
return ctype_digit( $id ) ? ( int ) $id : '0';

01-10-2008, 04:13 AM
Yes regex is not necessary in this case but I still noticed this:

^ and $ don't act as anchors unless you add the m modifier
so change it to:

EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum