is checking it's a number enough?
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!
Andy
pr0gr4mm3r posted this at 14:58 — 12th September 2008.
He has: 1,502 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;
?>
andy206uk posted this at 15:05 — 12th September 2008.
He has: 1,758 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!
greg posted this at 16:03 — 12th September 2008.
He has: 1,581 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
?>
JeevesBond posted this at 20:15 — 12th September 2008.
He has: 3,956 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
printf
style. 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!
Want to join the discussion? Create an account or log in if you already have one. Joining is fast, free and painless! We’ll even whisk you back here when you’ve finished.