When I work on PHP database driven websites, I'm always careful to sanitize data with mysql_escape_string() before inserting into the database.
However, if an input type is expected to be a number, is it enough to simply check it with is_numeric() before inserting into the db?
Surely, if it validates as a number there's no possible way that it could also contain something malicious?
Opinions? Thoughts?
Thanks guys!
Andyk
Blog of a Web Designer
Give a man a fish and you feed him for a day. Teach him to use the Net and he won't bother you for weeks.






pr0gr4mm3r posted this at 14:58 — 12th September 2008.
He has: 978 posts
Joined: Sep 2006
Yup, I will often type cast it to an integer instead of escaping it if I know it should be a number. Don't know if that saves CPU time or not, but it further cleans that piece of data.
<?php$some_number = (int)$some_number;
?>
PHP Starter
andy206uk posted this at 15:05 — 12th September 2008.
He has: 1,754 posts
Joined: Jul 2002
Wow - quick response!
I'm not familiar with type casting in PHP, but I'm definitely going to read up on it now!
Thanks!
Andyk
Blog of a Web Designer
Give a man a fish and you feed him for a day. Teach him to use the Net and he won't bother you for weeks.
greg posted this at 16:03 — 12th September 2008.
He has: 743 posts
Joined: Nov 2005
Another note, it also works for numeric strings as well
<?php$var = 2; //is_numeric() returns true
$var = "2"; //is_numeric() returns true
?>
www.worldwide-web.co.uk
www.hotnews-4u.com
In a world without fences and walls, who needs Gates and Windows?
JeevesBond posted this at 20:15 — 12th September 2008.
He has: 3,720 posts
Joined: Jun 2002
Curse you for being faster than me pr0gr4mm3r, you said exactly what I was going to.
Personally I love how Drupal does data sanitation, in a
printfstyle. For example, to get Andy's user account we might run:<?php$result = db_query("SELECT * FROM users WHERE username='%s' AND number_of_posts > %d", "andy206uk", 1000);
?>
Sanitation is part of the
db_query()function, so you never have to worry about it. I advise you to borrow from this and create your own similar functions.a Padded Cell our articles site!