Harshal
Harshal

Reputation: 3622

Json_encode/decode in php

I have an array on view $all_set which contain some ids.now i want to pass this array in controller using form submit.for that i used the j son encode and decode.

on my view:

<?php $all_set=json_encode($all_set); ?>

<input type="hidden" name="all_set" value="<?php echo serialize($all_set); ?>">

the above value contains(as i saw in page source):

<input type="hidden" name="all_set" value="s:26:"{"0":"1","5":"2","13":"3"}";">

Now on controller:

$result=$this->input->post('all_set');

           $result= unserialize($result);
           $result=json_decode($result);
           print_r($result); die;

This gives me error and i am not getting any array on controller. Error:

Message: unserialize() [function.unserialize]: Error at offset 0 of 5 bytes

Why is this so? please Help.

Upvotes: 0

Views: 1467

Answers (2)

Marcin Orlowski
Marcin Orlowski

Reputation: 75629

You have to add htmlspecialchars() to your serialize.

<input type="hidden" name="all_set" value="<?php echo htmlspecialchars(serialize($all_set)); ?>">

EDIT

Why this solves the problem? Let's see the OP's quoted output first:

value="s:26:"{"0":"1","5":"2","13":"3"}";">
      ^     ^

I added ^ to mark the problem source - your value included quotation marks, which made browser see this input more less like this:

value="s:26:" {"0" "1" , "5" : "2","13":"3"}";">

It simply closed the string once it found matching ". There're are special characters in HTML, including <, >, &, " which have to be converted to entities if they are expected to be passed literaly. So by calling htmlspecialchars() we convert all these characters and the markup would look like this:

value="s:26:&quot;{&quot;0&quot;:&quot;1&quot;,&quot;5&quot;.....

Browser interprets it now correctly, displays correctly and sends back correctly but to not treat it as part of markup.

EDIT 2

In fact unserialize is quite uselss in your code. Get rid of serialize()/unserialize() completetly - your json encoded data is just pure string, so you need only htmlspecialchars().

Upvotes: 5

MagePal Extensions
MagePal Extensions

Reputation: 17656

Try

<input type="hidden" name="all_set" value="<?php echo base64_encode($all_set); ?>">

$result= base64_decode($result);
$result=json_decode($result);

Upvotes: 1

Related Questions