how to pass an array in GET in PHP?

后端 未结 12 935
萌比男神i
萌比男神i 2020-11-28 14:37
$idArray = array(1,2,3,4);

can I write this line in HTML?

12条回答
  •  -上瘾入骨i
    2020-11-28 14:56

    Another option is to json_encode then base64_encode then urlencode then you can pass that into a get request.

    $idArray = [1,2,3,4];
    $urlArray = urlencode(base64_encode(json_encode($idArray)));
    $fullURL = 'https://myserver/mypath/myscript.php?arr=' . $urlArray;
    

    On receiving you can get back to the original array by urldecode then base64_decode then json_decode.

    $idArray = json_decode(base64_decode(urldecode($_GET["arr"])));
    

    As other have mentioned you can use serialize and unserialize but it is considered to be more secure to use json_encode and json_decode instead. Also as of PHP7 unserialize has a second parameter, for more info see https://github.com/kalessil/phpinspectionsea/blob/master/docs/security.md#exploiting-unserialize

    You may not need to use the base64_encode and base64_decode but I recommend it. It will cost you some processing resources but will result in a shorter URL saving you network resources. Keep in mind that if your working with large arrays you may excede the limits of the allowed length of get requests for your server.

提交回复
热议问题