Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sanitizing when storing serialized array

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);
like image 636
Chaim Avatar asked Feb 23 '23 08:02

Chaim


1 Answers

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);
like image 200
brianreavis Avatar answered Feb 24 '23 22:02

brianreavis