如何在php中增加会话值

时间:2016-08-09 07:21:08

标签: php login session-variables increment

我正在使用登录系统。我的登录表单发布到check.php。

如果用户详细信息不正确,我试图编写一个函数来测试失败的登录尝试次数。

<?php
//from check.php
if (blah)
{
    $_SESSION['error'] = "<strong>Details not correct.</strong> Please try again.";     
    //$_SESSION['email'] = $email;
    $_SESSION['attempts'] = 1; //first attempt
    if(isset($_SESSION['attempts']))
    {
        $_SESSION['fail'] = $_SESSION['attempts']++; //increment
    }
    //$_SESSION['fail'] is echo'd on my login form 
}

6 个答案:

答案 0 :(得分:1)

此代码除逻辑没有错误

如果以下代码在任何函数内。然后,显然它会在递增到2后停止。因为,$_SESSION['attempts']在每个函数调用中都设置为1。您必须在该函数调用之前设置$_SESSION['attempts'] = 1

<?php
if (blah)
{
    $_SESSION['error'] = "<strong>Details not correct.</strong> Please try again.";
    if(isset($_SESSION['attempts']))
    {
          $_SESSION['fail'] = $_SESSION['attempts']++; //increment
    }
}
  

登录表单发布到check.php,其中包含该功能   如果生成错误,反过来又会重定向回登录表单。   〜@ user3464091

如果是那个场景,那么请修改我的代码。

解释:在这种情况下,每次提交登录凭据后,它都会进入此功能。并且,如果已定义$_SESSION['attempts']。然后,它将增加到1.并且,如果未设置$_SESSION['attempts']。然后,它将初始化为1。

[注意:成功登录后不要忘记unset($_SESSION['attempts']);。]

<?php
if (blah)
{
  $_SESSION['error'] = "<strong>Details not correct.</strong> Please try again.";
  if(isset($_SESSION['attempts']))
  {
        $_SESSION['fail'] = $_SESSION['attempts']++; //increment
  } else {
        $_SESSION['attempts'] = 1;
  }
}

答案 1 :(得分:0)

删除$ _SESSION [&#39;尝试&#39;] = 1;在你的if条件之前

它应该是这样的......

if(isset($_SESSION['attempts'])) { $_SESSION['fail'] = ++$_SESSION['attempts']; } else { $_SESSION['attempts'] = 1; }

答案 2 :(得分:0)

你可以使用:

简单地增加它
$_SESSION['fail']= $_SESSION['attempts']+1;

它遇到的问题是它首先定义会话变量然后执行程序。 因此,除非尚未设置变量,否则请确保不设置变量。

那是:

if(!isset($_SESSION['attempts'])) { $_SESSION['attempts']=1;}

然后继续代码。

答案 3 :(得分:0)

在将会话值存储在变量中之后,您将会话值递增。改变

$_SESSION['fail'] = $_SESSION['attempts']++;

$_SESSION['fail'] = ++$_SESSION['attempts'];

此外,在$_SESSION['attempts']存储失败的尝试,否则它不会超过2。

$_SESSION['attempts'] = $_SESSION['fail'];

答案 4 :(得分:0)

使用代码就像

一样
//from check.php
if (blah)
{
    $_SESSION['error'] = "<strong>Details not correct.</strong> Please try again.";     
    //$_SESSION['email'] = $email;

    if(!isset($_SESSION['attempts']))
    {
        $_SESSION['attempts'] = 1; //first attempt
    }
    else
    {
       $_SESSION['attempts']++; //increment
    }
    $_SESSION['fail'] = $_SESSION['attempts'];

//$_SESSION['fail'] is echo'd on my login form 
}

答案 5 :(得分:0)

<?php 
if (blah)
{
$_SESSION['error'] = "<strong>Details not correct.</strong> Please try again.";     
//$_SESSION['email'] = $email;

if(isset($_SESSION['attempts'])) // check session attempts exist
{
    $_SESSION['fail'] = $_SESSION['attempts']++; //session exist so do increment
}
else
{
    $_SESSION['attempts'] = 1; //  session attempts not exist condition so make first attempt
}


//$_SESSION['fail'] is echo'd on my login form 
}