MySQL database contains quotes encoded and unencoded and it's breaking javascript

倖福魔咒の 提交于 2019-12-11 15:20:41

问题


Example database value is '12345' which is assigned to a PHP variable $name.

This value is used in a javacript onclick event for example:

onclick="assign('<?php echo $name;?>')

What is the best way to deal with this?

onclick="assign('<?php echo $name;?>')
// output: onclick="assign(''12345'')

onclick="assign('<?php echo htmlspecialchars($name);?>')
// output: onclick="assign('&#39;12345'')

onclick="assign('<?php echo addslashes($name);?>')
// output: onclick="assign(''12345\'')

onclick="assign('<?php echo htmlspecialchars(addslashes($name));?>')
// output: onclick="assign('&#39;12345\'')

The last version works but I'm thinking there must be a better method.


回答1:


You should use language aware escaping routines where possible. addslashes is almost never the right choice.

In this case, json_encode will do the job as JSON is a subset of the bit of JavaScript that describes literals. Note it will also add the quotes to indicate that it is a string.

Once you make it safe for JavaScript, your existing choice of htmlspecialchars is the right one to make that JavaScript safe for embedding in an HTML attribute value.

onclick="assign(<?php echo htmlspecialchars(json_encode($name));?>)

You could also consider using a data- attribute to store the data in, and then binding your event handlers with addEventListener.



来源:https://stackoverflow.com/questions/46728198/mysql-database-contains-quotes-encoded-and-unencoded-and-its-breaking-javascrip

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