PHP"如果"条件错误

时间:2015-08-19 12:16:39

标签: php if-statement random

if条件出错。我正在尝试生成5digit random no,并验证随机no和文本框值($_POST['otp1'])等于移动到thank.php页面,否则显示弹出错误。

我做了所有事情,如果文本框值和$otp值相等,则显示弹出消息。

以下是代码

otp.php

<form action="otp.php" method="post">
<label>Mobile :</label>
<input type="text" name="mobile" /> <br /><br />
<label>OTP :</label>
<input type="text" name="otp1" /> <br /><br />
<input type="submit" name="send" value="Verifiy" />
</form>

<?php

$otp = intval( "0" . rand(1,9) . rand(0,9) . rand(0,9) . rand(0,9) . rand(0,9) );
echo $otp;

if(isset($_POST['send']))
{

    $mobile = $_POST['mobile'];
    $otp_no = $_POST['otp1'];

    if($otp_no != $otp) \\ Condition not work
    {
        echo "<script>alert('Your OTP is Worng'); window.location.replace(\"otp.php\");</script>";
    }
    else
    {
        header('Location: thank.php');

    }
}
?>

2 个答案:

答案 0 :(得分:2)

当页面重新加载时,$otp被重新生成。所以永远不会匹配。试试 -

sesstion_start();

if(isset($_POST['send']))
{

    $mobile = $_POST['mobile'];
    $otp_no = $_POST['otp1'];

    if($otp_no !== $_SESSION['otp']) \\ Check identical
    {
        echo "<script>alert('Your OTP is Worng');window.location.replace(\"otp.php\");</script>";
    }
    else
    {
        unset($_SESSION['otp']); // Unset the otp in session
        header('Location: thank.php');

    }
} else {
    $_SESSION['otp'] = intval( "0" . rand(1,9) . rand(0,9) . rand(0,9) . rand(0,9) . rand(0,9) );
    echo $_SESSION['otp'];
}

答案 1 :(得分:1)

问题是在表单提交中更改了otp代码。所以你必须将otp代码存储在隐藏元素中,并将其与用户输入的otp值进行比较。

<?php
$otp = intval( "0" . rand(1,9) . rand(0,9) . rand(0,9) . rand(0,9) . rand(0,9) );
echo $otp;
?>
<form action="test1.php" method="post">
<label>Mobile :</label>
<input type="text" name="mobile" /> <br /><br />
<label>OTP :</label>
<input type="hidden" name="otp" value="<?=$otp?>" /> 
<input type="text" name="otp1"  /><br /><br />
<input type="submit" name="send" value="Verifiy" />
</form>

<?php

//$otp = intval( "0" . rand(1,9) . rand(0,9) . rand(0,9) . rand(0,9) . rand(0,9) );
//echo $otp;

if(isset($_POST['send']))
{
  $mobile = $_POST['mobile'];
  $otp_no = $_POST['otp1'];
  $otp = $_POST['otp'];

  if($otp_no != $otp) // Condition not work
  {
      echo "<script>alert('Your OTP is Worng'); </script>";
  }
  else
  {
      echo "success";

  }
}
?>