Ezilon.com - Target Your Audience, be Seen in Your Region

is checking it's a number enough?

You are viewing this site as a guest. Join our community to get your questions answered and share knowledge. Active members may advertise and ask for a website critique.
andy206uk's picture
DeveloperModerator

He has: 1,754 posts

Joined: Jul 2002

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's picture
ModeratorSponsor

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;
?>
andy206uk's picture
DeveloperModerator

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.

DeveloperModerator

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's picture
Moderator

He has: 3,720 posts

Joined: Jun 2002

Curse you for being faster than me pr0gr4mm3r, you said exactly what I was going to. Smiling

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. Smiling

a Padded Cell our articles site!

Subscribe to this feed: Syndicate content