存储随机值,$ _SESSION和$ _POST问题

时间:2017-01-05 17:02:10

标签: php html session post

我正在制作类似于captha的东西,不工作的部分是IF,在if(isset($ _ POST ['submit']))下,总是返回false。我认为。 尝试了很多没有运气的方法...... 无论如何,我已经按照这个解决方案https://stackoverflow.com/a/21504949/4167976没有成功。

这是我的测试php和html:

<?php
session_start();
$char = "abcdefghijklmnopqrstuvwxyz1234567890";
$code = $char[rand(0,35)].$char[rand(0,35)].$char[rand(0,35)].$char[rand(0,35)].$char[rand(0,35)].$char[rand(0,35)];
$_SESSION["testcode"] = $code;
echo $_SESSION["testcode"]."<br>"; // echo here only for testing

if(isset($_POST['submit'])) {
    $code1 = mb_substr($_POST['fullcode'], 0, 5);
    $code2 = mb_substr($_POST['fullcode'], -6);

    if ($code2 == $_SESSION["testcode"])
        {echo "The code is correct!";}
    else
        {echo "Wrong code!";}

    // unset($_SESSION['testcode']); // ???
}

?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body>

<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<input type="text" name="fullcode">
<input type="Submit" name="submit" value="Submit!">
</form>

</body>
</html>

请告诉我我错在哪里和哪里......谢谢! :)

修改

<?php
session_start();

if (!isset($_SESSION["testcode"])) {
    $char = "abcdefghijklmnopqrstuvwxyz1234567890";
    $code = $char[rand(0,35)].$char[rand(0,35)].$char[rand(0,35)].$char[rand(0,35)].$char[rand(0,35)].$char[rand(0,35)];
    $_SESSION["testcode"] = $code;
}

if(isset($_POST['submit'])) {
    $code1 = mb_substr($_POST['fullcode'], 0, 5);
    $code2 = mb_substr($_POST['fullcode'], -6);

    if ($code2 === $_SESSION["testcode"])
        {echo "The code is correct!<br>";}
    else
        {echo "Wrong code!<br>";}

    unset($_SESSION['testcode']);
    $char = "abcdefghijklmnopqrstuvwxyz1234567890";
    $code = $char[rand(0,35)].$char[rand(0,35)].$char[rand(0,35)].$char[rand(0,35)].$char[rand(0,35)].$char[rand(0,35)];
    $_SESSION["testcode"] = $code;
}
?>

最后,如果条件为假,请获取新代码!

1 个答案:

答案 0 :(得分:0)

<?php
session_start();

// first request.
// if not set session 'testcode' and set it, else do nothing.
// prevent session be covered.
if (!isset($_SESSION["testcode"])) {
    reFreshCode();
}

if(isset($_POST['submit'])) {
    $code1 = mb_substr($_POST['fullcode'], 0, 5);
    $code2 = mb_substr($_POST['fullcode'], -6);
    if ($code2 == $_SESSION["testcode"])
        echo "The code is correct!";
    else {
        // get a new code IF the condition is false!
        echo "Wrong code!";
        echo “new code:”.reFreshCode();
    }
}

function reFreshCode() {
    $char = "abcdefghijklmnopqrstuvwxyz1234567890";
    $code = $char[rand(0,35)].$char[rand(0,35)].$char[rand(0,35)].$char[rand(0,35)].$char[rand(0,35)].$char[rand(0,35)];
    return $_SESSION["testcode"] = $code;
}