Jump to content

Data sanitization with intval() considered harmful


Jacques1

Recommended Posts

Hi,

 

I've noticed that many members routinely recommend intval() for “sanitizing” user input. I think this is a very bad idea for a couple of reasons:

  • PHP integers are stored in 32 bits or 64 bits depending on the platform. This is not enough to cover all MySQL integer types. For example, a 32-bit PHP integer can neither hold an INT UNSIGNED nor a BIGINT. And even a 64-bit PHP integer cannot hold a BIGINT UNSIGNED. That's obviously a problem and can lead to very nasty truncation bugs.
  • Silently changing the user input is very confusing and potentially harmful. Let's say the user tries to delete a record, but the provided ID is not numeric. This is clearly an error. Either the user has entered a wrong value, or there's an application bug. In any case, the request cannot be processed safely and should be rejected. What the intval() does instead is turn the invalid input into a “random” ID and pass it on to the database system to delete the record. Bad idea!
  • Many people already struggle to understand the difference between mysql_real_escape_string(), addslashes(), htmlentities(), filter_var() etc. Now we have yet another function in the ever-growing pool of “sanitize” functions. This doesn't really help.

So I think intval() should never be used for data “sanitization”. Just use the appropriate escape function like mysql_real_escape_string().

I'm aware that the MySQL extension is deprecated. But many people still use it (as you can see in this forum), so they need a way to escape their data. And the right function for this is mysql_real_escape_string() as opposed to intval().

 

If you use a modern database extension, you shouldn't rely on manual escaping at all and instead pass the data through the parameters of a prepared statement.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.