RazorFinger
RazorFinger

Reputation: 241

Why is my unserialize returning empty?

This could be a duplicate, but i couldn't find any one that helped.

I'm trying to pass an array of all the data to another page, throught the post method of a form. It looks like this:

        <form method="post" action="../resource_load/export.php" target="_blank">
        <input type="hidden" name="tipo" value="<?=$_GET['tipo']?>">
        <input type='hidden' name='excel_array' value='<?php echo htmlentities(serialize($_SESSION['excel_array']))?>'>
        <input  type='submit' class='submit' id='btnExport' value='Export to Excel' />

So here i serialize the $_SESSION data. and this is what it looks like:

    value="a:1:{s:12:"dpi_strategy";a:1:{s:5:"Plan1";a:1:{i:0;a:9:{i:0;s:3:"PCR";i:1;s:11:"Description";i:2;s:4:"Task";i:3;s:8:"Resource";i:4;s:13:"Baseline Plan";i:5;s:10:"Trend Date";i:6;s:4:"User";i:7;s:20:"Data Inicialização";i:8;s:6:"Status";}}}}

And here is where i unserialize:

    $Excel_array = htmlentities(unserialize($_POST['excel_array']));

Yet, it returns null. Why is that?

Upvotes: 1

Views: 3080

Answers (2)

Xorifelse
Xorifelse

Reputation: 7911

If you do this, use htmlentities() to encode and html_entity_decode() to decode with raw values.

Secondly, I don't believe it is a good idea to output the data of serialize and unserialize user submitted data. The reason being is code injection that is a major security issue.

Instead, use json_encode() and json_decode(). Now because I see you have special chars in your array Data Inicialização you are indeed correct to convert those characters to another entity, but aslong if you have everything UTF-8 it will work.

<input type='hidden' name='excel_array' value='<?php echo json_encode($_SESSION['excel_array']) ?>'>

And:

# ../resource_load/export.php 
var_dump(json_decode($_POST['excel_array']);

Upvotes: 2

CatalinB
CatalinB

Reputation: 581

<?php

    $temp = array();
    $temp['aaa'] = "aaaaaaaaaaaaaaaaaaaaaaa";
    $temp['bbb'] = "bbbbbbbbbbbbbbbbbbbbbbb";
    $temp['ccc'] = "ccccccccccccccccccccccc";

    $arr = array();
    $arr['excel_array'] = $temp;


?>

 <form method="post" action="">
     <input type='hidden' name='excel_array' value='<?php echo htmlentities(serialize($arr['excel_array']))?>'>
    <input  type='submit' class='submit' id='btnExport' value='Export to Excel' />

</form>


<?php


if( isset($_POST['excel_array']) ) {
    echo "<pre>";
    $Excel_array = unserialize($_POST['excel_array']);
    print_r($Excel_array);
}


?>

remove htmlentities from unserialize because you will unserialize an array and htmlentities use strings

Upvotes: 0

Related Questions