0

I create a symfony2 command with one argument. This argument is the result of serialize($array) function.

But, inside the command I'm not able to unserialize() the received argument, i always got an error:

Notice: unserialize(): Error at offset 5 of 48 bytes in ...

This is a example of the array i want to send to the command:

$array = array('key1' => '$value1', 'key2' => '$value2')

When i serialize the array (serialize($array)) this is the result:

a:2:{s:4:"key1";s:7:"$value1";s:4:"key2";s:7:"$value2";} 

I was thinking: maybe the problem is due to double quotes in the string (remember, is to send to a command as parameter), then, i apply the addslashes function:

addslashes(serialize($array)) 

This is the result:

a:2:{s:4:\"key1\";s:7:\"$value1\";s:4:\"key2\";s:7:\"$value2\";}

but im still receiving the same error when i try to unserialize the string inside the command execute() function.

Any idea?

1 Answer 1

2

SOLVED!!! the problem is with the operative system command line and the double quotes. There is a way to serialize the array and avoid double quotes as parameter in the command: encoding base64.

The solution is to encode the serialized array:

$serialized = serialize(array('key1' => 'value1', 'key2' => 'value2'));
//$serialized => a:2:{s:4:"key1";s:6:"value1";s:4:"key2";s:6:"value2";}

$base64 = base64_encode($serialize);
//$base64 => YToyOntzOjQ6ImtleTEiO3M6NjoidmFsdWUxIjtzOjQ6ImtleTIiO3M6NjoidmFsdWUyIjt9 

As you can see there is no quotes in $base64(that's one of the goals of base64_encode() ) Then, you can easily decode the string with base64_decode

$serialized = base64_decode($base64);
//$serialized => a:2:{s:4:"key1";s:6:"value1";s:4:"key2";s:6:"value2";}

$array = unserialize($serialized);
//$array => array('key1' => 'value1', 'key2' => 'value2')

I hope this help somebody

Sign up to request clarification or add additional context in comments.

3 Comments

Its not that practical, you need to encode separately, then paste it in your console. On my side (Windows with PHPStorm console) it works just with adding backslashes before doublequotes. php bin/console my:myCommand {\"foo\":\"bar\"}
@FabianPicone what happens if you have escaped double quotes in your code?
@vitoriodachef Good question, i tried it out, you have to escape the string escapes too {\"foo\":\"b\\\"a\\\"r\"}.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.