Pass a serialized object through a form

0

I'm trying to pass a serializado object to a form, to pick it up and not have to re-create it on the next page, but I do not print the string correctly in the input that I'm printing on. My code is as follows:

class Objeto{

    public $id;
    public $nombre;
    public $atributos;

    public function __construct($id, $nombre, $atributos){

        $this->id=$id;
        $this->nombre=$nombre;
        $this->atributos=$atributos;

    }

}

$objeto= new Objeto(32,'camiseta','de color verde');

$serializado=serialize($objeto);
?>

Then I have a form in which I print the serialized object:

<form method="post" action="pasando-serializado.php" >
   <input type="text" name="serializado" value="<?php echo $cadena;?>" lenght=1000 style="width: 50%"/>
   <button type="submit">Enviar</button>
</form>

And finally a file in which I pick up the post of the form:

    $serializado=$_POST['serializado'];

$unserializado=unserialize($serializado);

echo '<pre>';
        var_dump($unserializado);
    echo '</pre>';

It returns the value "O: 6".

Does anyone know why this happens? It is assumed that if what you return the serialize is a chain you should be able to print where you want, right?

Thank you very much for your help ;-)

    
asked by IreneA 04.12.2017 в 17:59
source

1 answer

1

The error occurs because the HTML is "breaks" when printing the result of serialize

For example, the result of $serializado=serialize($objeto); is:

O:6:"Objeto":3:{s:2:"id";i:32;s:6:"nombre";s:8:"camiseta";s:9:"atributos";s:14:"de color verde";}

When you print this value in value of input , it is cut off when the first double quote is detected ( " ). Demo:

console.log(document.getElementById('serializado').value)
<input type="text" id="serializado" value="O:6:"Objeto":3:{s:2:"id";i:32;s:6:"nombre";s:8:"camiseta";s:9:"atributos";s:14:"de color verde";}" lenght=1000 style="width: 50%"/>

Solution:

You could use htmlspecialchars to escape the special characters and thus avoid the HTML "break"

Example:

<input type="text" name="serializado" value="<?php echo htmlspecialchars($cadena);?>" lenght=1000 style="width: 50%"/>

Demo:

console.log(document.getElementById('serializado').value)
<input type="text" id="serializado" value="O:6:&quot;Objeto&quot;:3:{s:2:&quot;id&quot;;i:32;s:6:&quot;nombre&quot;;s:8:&quot;camiseta&quot;;s:9:&quot;atributos&quot;;s:14:&quot;de color verde&quot;;}" lenght=1000 style="width: 50%"/>
    
answered by 04.12.2017 в 18:12