How do you set a php cookie with multiple values?

后端 未结 4 1079
面向向阳花
面向向阳花 2020-12-18 04:37

I want to create a php cookie that stores the username and the userid. Or is it better to just use one to get the other?

4条回答
  •  孤城傲影
    2020-12-18 04:52

    I know it's an old thread, but this might save a future me some headache. The best way I believe would be to serialize/unserialize the data.

    setcookie('BlueMonster', serialize($cookiedata);
    $arCookie = unserialize($_COOKIE['BlueMonster']);
    

    (hijacked from https://www.brainbell.com/tutorials/php/Saving_Multiple_Data_In_One_Cookie.htm since it was far more complete than I would have thrown together in 5 mins)

     $value) {
          $cookiedata[$name] = $value;
        }
        setcookie('cookiedata',
          serialize($cookiedata),
          time() + 30*24*60*60);
      }
      function getAllCookieData() {
        if (isset($_COOKIE['cookiedata'])) {
          $formdata = $_COOKIE['cookiedata'];
          if ($formdata != '') {
            return unserialize($formdata);
          } else {
            return array();
          }
        } else {
          return null;
        }
      }
      function getCookieData($name) {
        $cookiedata = getAllCookieData();
        if ($cookiedata != null &&
          isset($cookiedata[$name])) {
            return $cookiedata[$name];
          }
        }
        return '';
      }
    ?>
    

提交回复
热议问题