PHP: Good way to reconstruct associative array from base64_decode

此生再无相见时 提交于 2021-02-10 18:14:06

问题


I want to base64_encode the parameters I send over the url.

Send:

<?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>

Receive:

<?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>

The encoding destroys the array, is there a convenient way to make an associative array out of the string again?

(the encoded url is not sensitive information, but I still do not want it to be flat out readable in the url. If there is a better way to pass this data between pages than what I am doing, let me know)


回答1:


parse_str is the inverse of http_build_query, so to recover your data:

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

Note that parse_str is harmful if called with only one argument.

And as an aside, you may not want to put this kind of information into the URL to begin with, since it can be easily disclosed to third parties, via the Referrer header, for instance.




回答2:


You can serialize() your array:

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

And then, on your end page unserialize() it:

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

Demo

However you need to be careful and do thorough checking of what you're receiving, since unserialize() will execute arbitrary code sent by the client. For example, I can serialize() my own array, then base64_encode() it, and pass it to the URL in the id parameter, and I can do pretty nasty stuff. So definitely check what you're getting in the request!

From the manual:

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 a comprehensive article on the matter. Give it a read!

As the manual says, you can also probably accomplish what you're trying to do with json_encode() and json_decode(), though the same warning remains, check that what you're getting is what you're supposed to get and sanitize it.



来源:https://stackoverflow.com/questions/48772407/php-good-way-to-reconstruct-associative-array-from-base64-decode

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!