问题
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(''12345'')
onclick="assign('<?php echo addslashes($name);?>')
// output: onclick="assign(''12345\'')
onclick="assign('<?php echo htmlspecialchars(addslashes($name));?>')
// output: onclick="assign(''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