views:

231

answers:

3

I'm just thinking about the best way to go about sanitizing my data to prevent injection attacks. Some people like to sanitize immediately before output, or immediately before insertion to the database... but the problem I see with this is twofold: (1) what if you miss a paramater/variable? (2) what if you're over-sanitizing? Not that it would hurt the output, but there's not much sense sanitizing stuff you already know is safe.

For example, in PHP instead of using $_GET and $_POST couldn't I wrap those with something like:

function get($var) {
    return my_sanitizer($_GET[$var]);
}

Or would that not be enough? Where else could malicious code sneak in?


After reading the answers below I realize this question was a bit foolish. It depends on if you're inserting to the database, or outputting HTML. In that case, perhaps it is better to do just before usage. That's okay though, it's easy enough to wrap output methods too...

+1  A: 

Personally, I'd always sanitize right before you insert into your database; that said, if you have a SQL based database parameterized SQL and sprocs are the way to go to ensure you aren't injecting anything that will cause harm.

Nate Bross
A: 

you can do a foreach for the $_POST or $_GET array and sanitize all

foreach($_POST as $key){

$_POST[$key] = addslashes($_POST[$key]) }

wnoveno
Except this function is not recommended. You should use the database-specific function, like mysqli_real_escape_string(), or better stored procedures.
Matthew Flaschen
Also sanitizing is not just for SQL, you need to have HTML and JS in mind if you output it on a page.
rslite
+3  A: 

There's more than one kind of sanitization, and more than one kind of injection. For instance, you'll generally want to sanitize or escape HTML and JS sometime before output. But the appropriate choice (e.g., stripping out all HTML, allowing HTML in a whitelist, making the user enter something else, or just escaping it so it shows as text) depends on the application.

As far as database injection, I agree with Nate you should use prepared statements for this (sometimes these use escaping internally, but that's not your concern) instead.

In summary, a homemade catch-all my_sanitizer you run immediately upon getting any data is probably the wrong choice.

Matthew Flaschen
Mark