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:"Username";i:1;s:8:"Password";i:2;s:11:"AccessLevel";}">
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\";}
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.
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']));
The "
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']));
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.
If you are using VARCHAR for that column, try to change your MySQL column to TEXT.