If I only sanitize GET and POST data, will I be safe from injection?

元气小坏坏 提交于 2019-12-02 07:43:41

问题


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:


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.




回答2:


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.




回答3:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!