Accessing $_COOKIE immediately after setcookie()

前端 未结 9 911
轻奢々
轻奢々 2020-11-22 05:43

I\'m trying to access a cookie\'s value (using $_COOKIE) immediately after calling the setcookie() function in PHP. When I do so, $_COOKIE[\

相关标签:
9条回答
  • 2020-11-22 06:16

    We can do this using AJAX calling.

    If we want to create cookies on button click so first create a AJAX call for creating cookies then the success of first AJAX calling we can call another AJAX for getting the cookies.

        function saveCookie() {
                var base_url = $('#base_url').val();
                var url = base_url + '/index/cookie';
                $.ajax({
                    'url': url,
                    'type': 'POST',
                    'success': function (data) {
                        if (data) {
                            var url = base_url + '/index/get_cookie';
                            $.ajax({
                                'url': url,
                                'type': 'POST',
                                'success': function (response) {
                                    var container = $('#show');
                                    if (response) {
                                        container.html(response);
                                    }
                                }
                            });
                        }
                    }
                });
            }
    
        <button type="button" onclick="saveCookie()">Save Cookie</button>
        <div id="show"></div>
    
    0 讨论(0)
  • 2020-11-22 06:18

    Using ob_start() and ob_flush() you can send the cookie to client and retrieve it in the same run time. Try this:

    ob_start();
    setcookie('uname', $uname, time() + 60 * 30);
    ob_flush();
    echo "Cookie value: " . $_COOKIE['uname'];
    
    0 讨论(0)
  • 2020-11-22 06:18

    I set a constant at the same time the cookie was created

    define('CONSTANT', true);
    return setcookie('cookiename', 'cookie value goes here', time() + 60 * 60 * 24 * 30, '/');
    

    I can then immediately do something by:

    if(isset($_COOKIE['cookiename']) || $_COOKIE['cookiename'] || defined('CONSTANT') && CONSTANT)
    
    0 讨论(0)
提交回复
热议问题