php 在 setcookie() 之后立即访问 $_COOKIE

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3230133/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 09:05:27  来源:igfitidea点击:

Accessing $_COOKIE immediately after setcookie()

phpcookies

提问by heapzero

I'm trying to access a cookie's value (using $_COOKIE) immediately after calling the setcookie()function in PHP. When I do so, $_COOKIE['uname']isn't set. Why?

我试图在 PHP 中$_COOKIE调用setcookie()函数后立即访问 cookie 的值(使用)。当我这样做时,$_COOKIE['uname']没有设置。为什么?

Note, however, that $_COOKIE['uname']is set as expected upon the next execution of the script, such as after a page refresh.

但是请注意,$_COOKIE['uname']在下次执行脚本时(例如在页面刷新后),它会按预期设置。

setcookie('uname', $uname, time() + 60 * 30);
echo "Cookie value: " . $_COOKIE['uname'];

采纳答案by Jason McCreary

$_COOKIEis set when the page loads, due to the stateless nature of the web. If you want immediate access, you can set $_COOKIE['uname']yourself or use an intermediate variable.

$_COOKIE由于网络的无状态特性,在页面加载时设置。如果您想立即访问,您可以自行设置$_COOKIE['uname']或使用中间变量。

For example:

例如:

if (isset($_COOKIE['uname'])) {
    // get data from cookie for local use
    $uname = $_COOKIE['uname'];
}
else {
    // set cookie, local $uname already set
    setcookie('uname', $uname, time() + 1800);  
}

回答by Mark Baker

The cookie isn't set until the response is sent back to the client, and isn't available in your PHP until the next request from the client after that.

cookie 在响应被发送回客户端之前不会设置,并且在此之后来自客户端的下一个请求之前在您的 PHP 中不可用。

However, when you set the cookie in your script, you can do:

但是,当您在脚本中设置 cookie 时,您可以执行以下操作:

setcookie('uname', $uname, time()+60*30);
$_COOKIE['uname'] = $uname;

回答by witrin

If you want to access a cookie's value immediately after calling the setcookie()you can't use $_COOKIE.The reason for this is in the nature of the protocol (see https://tools.ietf.org/html/rfc6265). When you use setcookie()it defines a Cookie to be sent along with the rest of the HTTP headers to the client(see http://php.net/manual/en/function.setcookie.php). But $_COOKIEon the other hand contains variables passed to the current script via HTTP Cookies from the client(http://php.net/manual/en/reserved.variables.cookies.php).

如果您想在调用后立即访问 cookie 的值setcookie(),则不能使用$_COOKIE. 其原因在于协议的性质(参见https://tools.ietf.org/html/rfc6265)。当您使用setcookie()它时,它定义了一个 Cookie 与其余的 HTTP 标头一起发送到客户端(请参阅http://php.net/manual/en/function.setcookie.php)。但$_COOKIE另一方面,包含通过来自客户端的HTTP Cookie 传递给当前脚本的变量(http://php.net/manual/en/reserved.variables.cookies.php)。

When you change $_COOKIEafter calling setcookie()- like some answers here recommend - it doesn't contain only the Cookies from the client any more. This could interferer with assumptions made in third party code used in your application and may result in unwanted site effects. So in general it's not good practice and it's only an option when the calls of setcookie()are part of your own code.

当您$_COOKIE在调用后更改时setcookie()- 就像这里推荐的一些答案一样 - 它不再只包含来自客户端的 Cookie。这可能会干扰在您的应用程序中使用的第三方代码中所做的假设,并可能导致不必要的站点效果。所以总的来说,这不是一个好习惯,它只是当 的调用setcookie()是您自己代码的一部分时的一种选择。

A clean and transparent way to get a value set with setcookie()within the same request is to use headers_list()(see http://php.net/manual/en/function.headers-list.php):

setcookie()在同一请求中获取值集的一种干净透明的方法是使用headers_list()(参见http://php.net/manual/en/function.headers-list.php

function getcookie($name) {
    $cookies = [];
    $headers = headers_list();
    // see http://tools.ietf.org/html/rfc6265#section-4.1.1
    foreach($headers as $header) {
        if (strpos($header, 'Set-Cookie: ') === 0) {
            $value = str_replace('&', urlencode('&'), substr($header, 12));
            parse_str(current(explode(';', $value, 1)), $pair);
            $cookies = array_merge_recursive($cookies, $pair);
        }
    }
    return $cookies[$name];
}
// [...]
setcookie('uname', $uname, time() + 60 * 30);
echo "Cookie value: " . getcookie('uname');

But notice this won't work in PHP CLI (e.g. PHPUnit). In such a case you could use third party extensions like XDebug (see http://xdebug.org/docs/all_functions#xdebug_get_headers).

但是请注意这在 PHP CLI(例如 PHPUnit)中不起作用。在这种情况下,您可以使用 XDebug 等第三方扩展(请参阅http://xdebug.org/docs/all_functions#xdebug_get_headers)。

回答by Joshua

You have to set the cookie variable by yourself if you need it immediately, by the time you load another page the real cookie would have been set as a result of the setcookie method.

如果您立即需要它,您必须自己设置 cookie 变量,当您加载另一个页面时,真正的 cookie 将被设置为 setcookie 方法的结果。

setcookie('name', $value, time()+60*30);
$_COOKIE ['name'] = $value;

回答by Sebastiaan Koopman

I had a similar problem where i used a function from a included file and solved it with a function that both returns the value of the cookie and sets the cookie.

我有一个类似的问题,我使用了一个包含文件中的函数,并用一个函数来解决它,该函数既返回 cookie 的值又设置 cookie。

function setCookie($input) {
  setcookie('uname', $input, time() + 60 * 30);
  return $input;
}

if(!isset($_COOKIE['uname'])) {
    $uname  = setCookie($whatever);
} else {
    $uname = $_COOKIE['uname'];
}

echo "Cookie value: " . $uname;

回答by Fakirchand Patidar

We can do this using AJAX calling.

我们可以使用 AJAX 调用来做到这一点。

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.

如果我们想在按钮单击时创建 cookie,那么首先创建一个 AJAX 调用来创建 cookie,然后第一个 AJAX 调用成功,我们可以调用另一个 AJAX 来获取 cookie。

    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>

回答by Will Soares

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()ob_flush()您可以将 cookie 发送到客户端并在同一运行时间内检索它。尝试这个:

ob_start();
setcookie('uname', $uname, time() + 60 * 30);
ob_flush();
echo "Cookie value: " . $_COOKIE['uname'];

回答by Robert Rocha

Your script's setcookie()function runs when the web browser requests the page for the first time, in your case the reload. This cookie is stored in the users browser and isn't available to your script running on the server until the next request, or in your case the next reload.

setcookie()当 Web 浏览器第一次请求页面时,您的脚本函数就会运行,在您的情况下是重新加载。此 cookie 存储在用户浏览器中,在下一次请求或下一次重新加载之前,您在服务器上运行的脚本不可用。

Upon the next request the browser sends that cookie to the server and the array $_COOKIEwill have the value that you initially set and the browser sent back upon the second request.

在下一个请求时,浏览器将该 cookie 发送到服务器,该数组$_COOKIE将具有您最初设置的值,浏览器将在第二个请求时发回。

回答by virtualLast

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

我在创建 cookie 的同时设置了一个常量

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)