How do I properly sanitize data received from a text area, when outputting it back into the text area?

老子叫甜甜 提交于 2019-11-30 13:31:57

问题


A user will input text in a textarea. It is then inserted directly into a mySQL database. I use trim, htmlentities, mysql_real_escape_string on it and I have magic quotes enabled. How should I sanitize it when outputting that data back into a textarea?

Thanks for your help. I've never been too sure on the correct way of doing this...


回答1:


You shouldn't use htmlentities when saving it. You should use htmlentities when displaying it. The rule of thumb is not to encode/sanitize the data until you need to. If you do htmlentities on it when you save then you have to do html_entity_decode on the text when the user wants to edit the input. So you sanitize for what you need and nothing more. When saving it, you need to sanitize for SQL injection, so you mysql_real_escape_string it. When displaying, you need to sanitize for XSS, so you htmlentities it.

Also, I am not sure if you saw Darryl Hein's comment, but you really do not want magic_quotes enabled. They are a bad, bad, thing and have been deprecated as of PHP 5.3 and will be gone altogether in PHP 6.




回答2:


In addition to Paolo's answer about when to use htmlentities(), unless you're using an old version of PHP, the correct way to sanitize for insertion into a mysql DB is to use Prepared Statements which are part of the mysqli extension. This replaces any need to use mysql_real_escape_string().

Other than that, I think you've got things covered.



来源:https://stackoverflow.com/questions/593238/how-do-i-properly-sanitize-data-received-from-a-text-area-when-outputting-it-ba

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