PHP how to stringify array and store in cookie

后端 未结 2 1114
旧时难觅i
旧时难觅i 2020-12-15 01:09

I got an array like this

$value = {array(\'id\'=>$id, \'email\'=>$email, \'token\'=>$token)}

I want to stringify the array then encode then store it in cooki

2条回答
  •  温柔的废话
    2020-12-15 01:34

    json_encode/json_decode

    $_COOKIE['login'] = json_encode($array);
    $array = json_decode($_COOKIE['login']);
    

    Can also use serialize/unserialize:

    $_COOKIE['login'] = serialize($array);
    $array = unserialize($_COOKIE['login']);
    

    Perhaps.


    UPDATE

    With this code:

     1234,
        'email' => 'example@example.com',
        'token' => base64_encode('abcDEF1234')
      );
    
      echo "Var Dump (initial):\r\n";
      var_dump($array);
    
      $serialized = serialize($array);
      echo "Serialized:\r\n".$serialized."\r\n";
    
      $unserialized = unserialize($serialized);
      echo "Unserialized:\r\n".$unserailized."\r\n";
      var_dump($unserialized);
    ?>

    You would generate the following:

    Var Dump (initial):
    array(3) {
      ["id"]=>
      int(1234)
      ["email"]=>
      string(19) "example@example.com"
      ["token"]=>
      string(16) "YWJjREVGMTIzNA=="
    }
    Serialized:
    a:3:{s:2:"id";i:1234;s:5:"email";s:19:"example@example.com";s:5:"token";s:16:"YWJjREVGMTIzNA==";}
    Unserialized:
    
    array(3) {
      ["id"]=>
      int(1234)
      ["email"]=>
      string(19) "example@example.com"
      ["token"]=>
      string(16) "YWJjREVGMTIzNA=="
    }
    

    EDIT2

    You're seeing the encoded value based on how the HTTP protocol transfers cookies. There are two headers in a cookie transfer: Set-Cookie & Cookie. One is server->client, other other is client->server, respectfully.

    When PHP sets the cookie (using setcookie e.g.) PHP is really just short-handing the following:

    setcookie('login',$serialized);
    

    which, in PHP translates to:

    header('Set-Cookie: login='.urlencode($serialized).'; '
          .'expires=Wed, 12-Jan-2011 13:15:00 GMT; '
          .'path=/; domain=.mydomain.com');
    

    If you had characters like : or a SPACE, the browser wouldn't know where the cookie's properties began and ended.

提交回复
热议问题