user3282988
user3282988

Reputation: 129

serialize & unserialize functions

I have an array that I'm converting into a string using serialize:

$.ajax({
    url: "admin/adminProccess.php",
    type: "get",
    data: $('#idPriv:checked').serialize().replace(/http%3A%2F%2F/g,'#http#')  + '&str=' + 'deleteAdmin',
    success: function(data) {

When the code is sending to the php page is in this format:

443d77a90e9eb5524fd4e305eb263885:0

So, I used the unserialize function to return into an array. But I don't why I'm getting a false response;

This is the code I used in the php page:

for ($i=0;$i<count($idPriv);$i++){
    $test=$_GET['idPriv'][$i];

    $test  = unserialize($test);;
    var_dump($test);
}

Am I doing something wrong?I

Upvotes: 0

Views: 509

Answers (2)

Gordon
Gordon

Reputation: 316969

From the jQuery's manual on serialize:

Serialize a form to a query string that could be sent to a server in an Ajax request.

So what it does is to take some form values and turn them into a query string like

single=Single&multiple=Multiple&multiple=Multiple3

From the PHP Manual on unserialize:

Creates a PHP value from a stored representation

That stored representation is unique to PHP and looks something like this:

O:1:"a":1:{s:5:"value";s:3:"100";}

In other words, you are trying to unserialize a query string, whereas PHP can only unserialize strings serialized with PHP's serialize.

With that said, the function to parse a query string in PHP would be

Abridged example from PHP Manual:

$str = "first=value&arr[]=foo+bar&arr[]=baz"; 
parse_str($str, $output);
echo $output['first'];  // value
echo $output['arr'][0]; // foo bar
echo $output['arr'][1]; // baz

Upvotes: 3

Dimitri Mestdagh
Dimitri Mestdagh

Reputation: 44675

Serialization is an environment specific process. If you serialize something in Java/PHP/JavaScript/... then it can only be deserialized using the same environment (at least, that's what you should expect).

The best think you can do is serialize your objects to a well known format, for example JSON. Then you could do the following in JavaScript:

JSON.stringify(myObject);

And in PHP:

<?php
    json_decode(myJson);
?>

Of course you could choose for another format (XML, comma seperated, query string, ...), the main clue is that you need to serialize/deserialize to a language that can be used by both environments. And JSON is probably the most obvious one (next to a query string).

Upvotes: 1

Related Questions