繁体   English   中英

在 PHP 中解码 Base64 编码的数组

[英]Decoding an Base64 encoded Array in PHP

我想在 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

问题出在哪里? 谢谢解答。

$all_infos变量是一个字符串,因为这是您从base64_decode($hash) 然后你不能期望它成为一个具有类似sample_id属性的数组。

这个特定的字符串有一个 PHP 表达式编码,但您需要解释该字符串。 一种方法是使用臭名昭著的eval函数。 请注意仅在您信任该字符串的来源时才使用它!

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

我知道这是一个较旧的问题,但似乎没有一个答案是正确的,绝对不建议使用 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'];

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM