在PHP中解码Base64编码的数组

时间:2018-02-03 15:47:01

标签: php base64

我想在php中解码并使用base64编码的数组,我的代码如下所示:

<?php
$hash = "YXJyYXkoInNhbXBsZV9pZCI9PiJObnJ5amZCV0p0STllalNRcnE2NHZIejFjc084RnVqUHRGRGk5WkdtM0Z3Vm9ieHprOSIsICJ4eF94eF94eHhfeHh4MSI9PiIwIiwgInNhbXBsZTIiID0+IjAiKQ==";
$hash_decoded = base64_decode($hash);
$all_infos = $hash_decoded;

$sample_id = $all_infos['sample_id'];
$xx_xx_xxx_xxx1 = $all_infos['xx_xx_xxx_xxx1'];
$sample2 = $all_infos['sample2'];
echo $sample_id;     ?>

,解码后的数组是

array("sample_id"=>"NnryjfBWJtI9ejSQrq64vHz1csO8FujPtFDi9ZGm3FwVobxzk9", "xx_xx_xxx_xxx1"=>"0", "sample2" =>"0")

我无法从阵列中获取信息。控制台说

PHP Warning:  Illegal string offset 'sample_id' in [...] on line 6
PHP Warning:  Illegal string offset 'xx_xx_xxx_xxx1' in [...] on line 7
PHP Warning:  Illegal string offset 'sample2' in [...] on line 8
a
问题出在哪里?谢谢你的回答。

3 个答案:

答案 0 :(得分:0)

$all_infos变量是一个字符串,因为这是您从base64_decode($hash)返回的内容。您不能指望它成为具有sample_id等属性的数组。

此特定字符串具有编码的PHP表达式,但您需要解释该字符串。一种方法是使用臭名昭着的eval函数。当您信任该字符串的来源时,请小心使用它!

eval('$all_infos = ' . $hash_decoded . ";");

答案 1 :(得分:0)

要解码数组的base64编码元素,请使用以下PHP代码:

$array = ["sample_id"=>"NnryjfBWJtI9ejSQrq64vHz1csO8FujPtFDi9ZGm3FwVobxzk9"];
array_walk($array, 'array_decode');
function array_decode(&$item) {
     $item = base64_decode($item);
}

答案 2 :(得分:0)

我知道这是一个比较老的问题,但是所有答案似乎都不正确,因此绝对不建议使用eval()。

据我所知,主要问题是您直接使用base64_encode对数组进行编码,从而将其转换为字符串,而无需首先对数组进行序列化(这将解决您的问题);因此,请确保您在使用PHP的功能之前:

 serialize ( mixed $value ) : string

以下是您的案例的完整示例:

// Step 1: Correctly format the original array with serialize to not lose their type and structure
$originalArray = ["sample_id"=>"NnryjfBWJtI9ejSQrq64vHz1csO8FujPtFDi9ZGm3FwVobxzk9", "xx_xx_xxx_xxx1"=>"0", "sample2" =>"0"];
// first serialize the array and then base64_encode it
$hashedArray =  base64_encode(serialize($originalArray));
// output : YTozOntzOjk6InNhbXBsZV9pZCI7czo1MDoiTm5yeWpmQldKdEk5ZWpTUXJxNjR2SHoxY3NPOEZ1alB0RkRpOVpHbTNGd1ZvYnh6azkiO3M6MTQ6Inh4X3h4X3h4eF94eHgxIjtzOjE6IjAiO3M6Nzoic2FtcGxlMiI7czoxOiIwIjt9
print_r($hashedArray);


// Step 2: Re-decoding the hash to use the array
$hash = "YTozOntzOjk6InNhbXBsZV9pZCI7czo1MDoiTm5yeWpmQldKdEk5ZWpTUXJxNjR2SHoxY3NPOEZ1alB0RkRpOVpHbTNGd1ZvYnh6azkiO3M6MTQ6Inh4X3h4X3h4eF94eHgxIjtzOjE6IjAiO3M6Nzoic2FtcGxlMiI7czoxOiIwIjt9";
$hashDecoded = unserialize(base64_decode($hash));
//output : Array ( [sample_id] => NnryjfBWJtI9ejSQrq64vHz1csO8FujPtFDi9ZGm3FwVobxzk9 [xx_xx_xxx_xxx1] => 0 [sample2] => 0 ) 
print_r($hashDecoded);
// Getting the information you want:
$sample_id = $hashDecoded['sample_id'];
$xx_xx_xxx_xxx1 = $hashDecoded['xx_xx_xxx_xxx1'];
$sample2 = $hashDecoded['sample2'];