问题
If I am storing a serialized array to a mysql database should I sanitize before or after using the serialize function. Or do I even need to sanitize at all?
For example:
$details['name'] = mysql_real_escape_string($_POST['name']);
$details['email'] = mysql_real_escape_string($_POST['email']);
$details['phone'] = mysql_real_escape_string($_POST['phone']);
$serializedDetails = serialize($details);
// Do SQL query
Or
$details['name'] = $_POST['name'];
$details['email'] = $_POST['email'];
$details['phone'] = $_POST['phone'];
$serializedDetails = mysql_real_escape_string(serialize($details));
Or perhaps on the second I can simply do:
$serializedDetails = serialize($details);
回答1:
Always use mysql_real_escape_string
when dealing with strings that might have quotation marks / slashes. If you don't, you'll get broken / malicious queries. The output of serialize()
sometimes has quotation marks / slashes, so you should use it. There's no need to serialize the each item of the array beforehand though.
$details['name'] = $_POST['name'];
$details['email'] = $_POST['email'];
$details['phone'] = $_POST['phone'];
$serializedDetails = mysql_real_escape_string(serialize($details));
Just as an example: serializing "hello" will give you: s:5:"hello"
.
$data = 's:5:"hello"';
$query = 'INSERT INTO tbl (data) VALUES ("' . $data . '")';
// leads to a syntax error from mysql
// (plus it's a huge security hole)
mysql_query($query);
来源:https://stackoverflow.com/questions/8238463/sanitizing-when-storing-serialized-array