PHP Serialize Successful, Unserialize Failure

2019-08-06 23:26发布

问题:

My PHP code serializes, but doesn't unserialize, what could be the problem?

$serializedColumns = serialize($columnNames);

I have the following resulting html, where i stored the serialized string into a hidden field:

<input id="columns_hidden" name="columns" type="hidden" value="a:3:{i:0;s:8:&quot;Username&quot;;i:1;s:8:&quot;Password&quot;;i:2;s:11:&quot;AccessLevel&quot;;}">

The request is sent to 'AddData.php', i where i have my unserialize code like this:

$columns =  unserialize($_REQUEST['columns']);

when i call print_r on $columns, it returns a blank string.

when i call print_r on $_REQUEST['columns'], it returns:

a:3:{i:0;s:8:\"Username\";i:1;s:8:\"Password\";i:2;s:11:\"AccessLevel\";}

回答1:

This is actually a comment, but I put it here for more attention: Don't do that.

Why? - Whenever you unserialize data provided by a request blindly, PHP does more than you think. This can create objects which are dangerous for your application and you can not do a thing against that.

The hidden input can be easily edited and manipulated with a DOM editor or JavaScript to include harmful code or malicious requests can be fired against your site bringing it down quickly.

Alternatives - Instead use some form of data that you can process more easily, for example, use json_encode / json_decode or a classic implode / explode:

$serializedColumns = implode(',', $columnNames);

and

$columns =  explode(',', $_REQUEST['columns']);

this is much more failsafe and sane because it's static data processing.



回答2:

It appears you are passing the result of serialize through htmlspecialchars. This will corrupt the serialized data. Use a different encoding method to make it safe for use as an html attribute value, i.e., base64_encode:

<?php
$serializedColumns = serialize($columnNames);
?>

<input id="columns_hidden" name="columns" type="hidden" value="<?php echo base64_decode($serializedColumns) ?>">

Then, in your processing script:

$columns =  unserialize(base64_decode($_REQUEST['columns']));


回答3:

The &quot; are probabably going in the way of serialize, as the ; is not escaped.

You could base64_encode the value and decode it afterwards:

$serializedColumns = base64_encode(serialize($columnNames));

to

$columns =  unserialize(base64_decode($_REQUEST['columns']));


回答4:

when your data is posted to PHP, it looks like good old magic quotes is injecting \ before all the delimiting quote marks. You have to unescape it (drop slashes) before you can decode/unserialize.



回答5:

If you are using VARCHAR for that column, try to change your MySQL column to TEXT.