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...
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.
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.
you can do a foreach for the $_POST or $_GET array and sanitize all
foreach($_POST as $key){
$_POST[$key] = addslashes($_POST[$key])
}
来源:https://stackoverflow.com/questions/1570458/if-i-only-sanitize-get-and-post-data-will-i-be-safe-from-injection