PHP:从 base64_decode 重建关联数组的好方法

PHP: Good way to reconstruct associative array from base64_decode

我想 base64_encode 我通过 url 发送的参数。

发送:

<?php 
    $product = array("productID"=>"13776", "name"=>"something", "availability"=>"1000");
    $url_details = "?id=" . base64_encode(http_build_query($product));
?>

<a href="details.php<?php echo $url_details; ?>" class="btn btn-primary btn-lg" role="button">Details</a>

接收:

<?php
    $details = base64_decode($_GET["id"]);
    // $product = what is the best way to reconstruct the array from $details?
?>
<p>
    Name: <?php echo $products["name"]; ?>
    ...
</p>

编码破坏了数组,有没有方便的方法把字符串重新做成关联数组?

(编码的 url 不是敏感信息,但我仍然不希望它在 url 中完全可读。如果有更好的方法在页面之间传递此数据比我在做什么,让我知道)

您可以 serialize() 您的数组:

<?php
$product = array("productID"=>"13776", "name"=>"something", "availability"=>"1000");
$url_details = base64_encode(serialize($product));

然后,在您的末页 unserialize() 它:

<?php
$details = unserialize(base64_decode($url_details));

Demo

但是您需要小心并彻底检查您收到的内容,因为unserialize()执行客户端发送的任意代码。比如我可以serialize()我自己的array,然后base64_encode()它,再传给id参数里的URL,就可以漂亮了讨厌的东西。所以一定要检查你在请求中得到了什么!

来自手册:

Warning

Do not pass untrusted user input to unserialize() regardless of the options value of allowed_classes. Unserialization can result in code being loaded and executed due to object instantiation and autoloading, and a malicious user may be able to exploit this. Use a safe, standard data interchange format such as JSON (via json_decode() and json_encode()) if you need to pass serialized data to the user.

Here's 一篇关于此事的综合文章。读一读!

如手册所述,您也可以使用 json_encode() and json_decode() 完成您尝试做的事情,尽管仍然存在相同的警告,检查重新得到的是你应该得到的并对其进行消毒。

parse_str 是 http_build_query 的倒数,因此要恢复您的数据:

parse_str(base64_decode($_GET["id"]), $details);

请注意,如果仅使用一个参数调用 parse_str 是有害的。

顺便说一句,您一开始可能不想将此类信息放入 URL,因为它很容易泄露给第三方,例如 via the Referrer header