Check if a PHP cookie exists and if not set its value

后端 未结 2 1433
日久生厌
日久生厌 2020-12-05 02:35

I am working on a multilingual site so I tried this approach:

echo $_COOKIE[\"lg\"];
if (!isset($_COOKIE[\"lg\"]))
    setcookie(\"lg\", \"ro\");
echo $_COOK         


        
2条回答
  •  攒了一身酷
    2020-12-05 02:51

    Answer

    You can't according to the PHP manual:

    Once the cookies have been set, they can be accessed on the next page load with the $_COOKIE or $HTTP_COOKIE_VARS arrays.

    This is because cookies are sent in response headers to the browser and the browser must then send them back with the next request. This is why they are only available on the second page load.

    Work around

    But you can work around it by also setting $_COOKIE when you call setcookie():

    if(!isset($_COOKIE['lg'])) {
        setcookie('lg', 'ro');
        $_COOKIE['lg'] = 'ro';
    }
    echo $_COOKIE['lg'];
    

提交回复
热议问题