基于cookie的无限循环php重定向


Infinite loop php redirect based on cookie

我目前正忙于编写注册页面。页面有三个步骤,每个步骤都有自己的cookie值。我想做的是检查cookie值,并在访问网站时将用户转移到正确的页面

示例:如果$_COOKIE["step"]的值为"step_two",则应重定向到:www.domain.com/register.php?step=your_details。如果cookie未设置,则不应重定向并停留在register.php页面上。

重定向工作得很好,但它进入了一个无限循环。我真的想不清了,因为我已经醒了将近24小时了。因此,如果有人能把我推向正确的方向,我将不胜感激。

一段代码:

$cookie_value = 'step_2';
setcookie("step",$cookie_value, time()+3600*24);
$cookie_not_set = true;
$cookie_step_two = false;
if (isset($_COOKIE['step'])) {
    if ($_COOKIE['step'] == 'step_2') {
        $cookie_not_set = false;
        $cookie_step_two = true;
        header('Location: ?step=your_details');
        exit();
    }
} else {
    $cookie_not_set = true;
}

谢谢。

您实际上没有在任何地方设置cookie值,因此它不会更改。这就是为什么你有一个无限循环。

CCD_ 1和CCD_。看起来你想要:

if ($_GET['step'] === 'your_details')`

这无论如何都比使用cookie要好。

您将不断输入if条件,因为您的cookie数据没有其他操作。

如果您的cookie设置为"step2",您将进入循环。没有任何更改,因此刷新页面。您将重新进入step_2条件并进入重定向。

我还假设你理解你的$_GET&$_COOKIE请求完全不同。如果没有,请参阅@Brads回答


停止这种无限循环的解决方案是:

if (isset($_COOKIE['step'])) {
    if ($_COOKIE['step'] == 'step_2') {
        $cookie_not_set = false;
        $cookie_step_two = true;
        $_COOKIE['step'] = 'step_3';
        header('Location: ?step=your_details');
        exit();
    }

但也要注意,您的真/假验证/更改是本地更改,在页面刷新时不会是绝对的

我相信你的问题是重定向没有改变你的cookie,所以如果cookie设置为step_2,你需要查看你重新传递的GET var;

$cookie_not_set = true;
$cookie_step_two = false;
if (isset($_COOKIE['step'])) {
    if ($_COOKIE['step'] == 'step_2') {
       if( !empty($_GET['step']) && $_GET['step'] == 'your_details' )
       {
          ... you have redirected and now can continue ...
       }
       else
       {
         // redirect and set the get var to signal to this script.
          $cookie_not_set = false;
          $cookie_step_two = true;
          header('Location: ?step=your_details');
          exit();
        }
    }
} else {
    $cookie_not_set = true;
}