PHP,变量未定义

时间:2015-01-30 03:17:32

标签: php

我正在尝试进行验证码验证,并且未定义其中一个变量。这是我的验证码生成器代码:

<?php
    $num = rand(1,3);

    switch($num) {
        case 1:
            $img = "";
            $answer = "nov 18th";
            break;
        case 2:
            $img = "";
            $answer = "jan 19th";
            break;
        case 3:
            img = "";
            $answer = "school bad";
            break;
    }
?>

现在这是我的脚本代码,用于检查验证码输入是否输入正确:

<?php
    ini_set('display_errors',1);

    print "<br /><br />";

    $captcha = $_POST['captcha-verif'];

    if ($captcha == $answer) {
        header('Location: recommend-action.php');
    }
    else {
        print "Incorrect Captcha. <a href='music.php'>Try Again</a>";
    }
?>

我一直收到这条消息:

  

注意:未定义的变量:在第9行的/var/www/tts/recommend-verify-captcha.php中回答

2 个答案:

答案 0 :(得分:0)

您需要一个会话变量:

<?php
    // start session here
    session_start();
    $num = rand(1,3);

    switch($num) {
        case 1:
            $img = "";
            // store answer in session variables. 
            $_SESSION['answer'] = "nov 18th";
            break;
        case 2:
            $img = "";
            $_SESSION['answer']  = "jan 19th";
            break;
        case 3:
            $img = "";
            $_SESSION['answer']  = "school bad";
            break;
    }
?>

在您的第二个代码段中,请务必再次开始会话。

<?php
    // restart session
    session_start();
    ini_set('display_errors',1);

    print "<br /><br />";

    $captcha = $_POST['captcha-verif'];

    // compare $captcha against answer stored in the session
    if ($captcha == $_SESSION['answer']) {
        header('Location: recommend-action.php');
    }
    else {
        print "Incorrect Captcha. <a href='music.php'>Try Again</a>";
    }
?>

答案 1 :(得分:-1)

您未在recommend-verify-captcha.php中声明回答变量,因此,此变量不存在。

根据您的代码,我看到您希望答案来自

<?php
$num = rand(1,3);

switch($num) {
    case 1:
        $img = "";
        $answer = "nov 18th";
        break;
    case 2:
        $img = "";
        $answer = "jan 19th";
        break;
    case 3:
        $img = "";
        $answer = "school bad";
        break;
}?>

所以你可以这样做

function getCapcha(){
    $num = rand(1,3);

    switch($num) {
        case 1:
            $img = "";
            $answer = "nov 18th";
            break;
        case 2:
            $img = "";
            $answer = "jan 19th";
            break;
        case 3:
            $img = "";
            $answer = "school bad";
            break;
    }
}

然后在recommend-verify-captcha.php文件中使用此功能,可能就像

一样
<?php
    ini_set('display_errors',1);

    print "<br /><br />";

    $captcha = $_POST['captcha-verif'];
    $answer = getCapcha();
    if ($captcha == $answer) {
        header('Location: recommend-action.php');
    }
    else {
        print "Incorrect Captcha. <a href='music.php'>Try Again</a>";
    }
?>