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

后端 未结 2 1431
日久生厌
日久生厌 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'];
    
    0 讨论(0)
  • 2020-12-05 02:52

    Cookies are only sent at the time of the request, and therefore cannot be retrieved as soon as it is assigned (only available after reloading).

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

    If output exists prior to calling this function, setcookie() will fail and return FALSE. If setcookie() successfully runs, it will return TRUE. This does not indicate whether the user accepted the cookie.

    Cookies will not become visible until the next loading of a page that the cookie should be visible for. To test if a cookie was successfully set, check for the cookie on a next loading page before the cookie expires. Expire time is set via the expire parameter. A nice way to debug the existence of cookies is by simply calling print_r($_COOKIE);.

    Source

    0 讨论(0)
提交回复
热议问题