对于同一页面验证返回true

时间:2013-05-03 15:52:11

标签: php javascript ajax validation

我在使用相同的页面AJAX / JavaScript / PHP Captcha验证码时遇到问题。原始代码来自http://www.phpcaptcha.org。我们使用第三方网站将所有表单数据存储到由多人编辑的数据库中。最近我们收到了大量的垃圾邮件,所以我们正试图实施这个Captcha。

我会切入这里追逐。每次都将代码设置为“return false”。如果满足某些条件,我需要它'返回true'。代码如下:

<?php
session_start(); // this MUST be called prior to any output including whitespaces and line breaks!


$GLOBALS['DEBUG_MODE'] = 1;
// CHANGE TO 0 TO TURN OFF DEBUG MODE
// IN DEBUG MODE, ONLY THE CAPTCHA CODE IS VALIDATED, AND NO EMAIL IS SENT
// EMAIL is edited out for school use
if( isset($_POST['captcha_code']))
{
$a = array("error"=>0);
print json_encode($a);
}
// Process the form, if it was submitted (Original Code called process_si_contact_form())
process_si_zoho1();

?>
<html>
<head>

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/prototype/1.7.0.0/prototype.js"></script>


<script type="text/javascript">
//variables not part of original code
    function reloadCaptcha()
    {
    //original code ElementId labled 'captcha_code'
        document.getElementById('captcha').src ='securimage_show.php?sid=' + Math.random();
    }

    var r, Submit;
function processForm()
{
    new Ajax.Request('<?php echo $_SERVER['PHP_SELF'] ?>', {
        method: 'post',
        //Original code did not state 'zoho1'
       parameters: $('zoho1').serialize(),
        onSuccess: function(transport) {
        //Re-edited for school use. Not original code
            try {
                r = transport.responseText.evalJSON();
                Submit = r.submit

                if (r.error == 0) {
                alert('Congrats!');
                reloadCaptcha();


                } else {

                    alert("There was an error with your submission.\n\n" + r.message);

                }
            } catch(ex) {

                alert("There was an error parsing the json");

            }

        },
        onFailure: function(err) {

            alert("Ajax request failed");
        }

    });
return Submit;
}
}
</script>

process_si-zoho1()如下:

<?php
//Original code process called 'process_si_contact_form())
function process_si_zoho1()
{
if ($_SERVER['REQUEST_METHOD'] == 'POST' && @$_POST['do'] == 'contact') {
    // if the form has been submitted

    foreach($_POST as $key => $value) {
        if (!is_array($key)) {
            // sanitize the input data
            if ($key != '-------') $value = strip_tags($value);
            $_POST[$key] = htmlspecialchars(stripslashes(trim($value)));
        }
    }

    $captcha = $_POST['captcha_code']; // the user's entry for the captcha code

    $errors = array();  // initialize empty error array


    if (sizeof($errors) == 0) {
        require_once dirname(__FILE__) . '/securimage.php';
        $securimage = new Securimage();

        if ($securimage->check($captcha) == false) {
            $errors['captcha_error'] = 'Incorrect security code entered';

        }
    }

   if (sizeof($errors) == 0) {
        // no errors, send the form
       //Edited out mail function from original code

//Changed JSON return array on successful validation to send new variable '$Submit' via serialized $entry
        $Submit = true;
        $entry = array('error' => 0, 'submit' => $Submit);
        die(json_encode($entry));
    } else {
        $errmsg = $captcha_error;
        foreach($errors as $key => $error) {
            // set up error messages to display with each field
            $errmsg .= " - {$error}\n";
            $Submit = false;
        }
//Added $Submit to the return array
        $return = array('error' => 1, 'message' => $errmsg, 'submit' => $Submit);
        die(json_encode($return));
    }


} // POST
} // function process_si_zoho1()


?>

点击提交按钮时会运行'processForm()'。我确定我在这里遗漏了一些非常简单的东西,我只是太介入了。我非常感谢你的帮助

我知道直到AJAX.Request()中的PHP运行才定义'Submit'的值,但我无法弄清楚如何从一开始就定义变量。仅供参考,变量'r'和'Submit'都是在函数本身之外声明的,因此是全局变量。如果我尝试将一个返回值插入到try / catch中,它将始终在catch中显示错误“解析json时出错”。此外,使用现在的代码,它总是会给我相同的错误并提交表单,因为提交的值为空。即使我将全局变量“提交”定义为“假”,它仍然会返回,就像它是空白一样。

如果在函数的底部声明了“return false”以外的任何内容,它将提交表单而不验证Captcha。我对这一切都很陌生,但我已经研究了将近2周,现在每天工作4-8小时,而且还没有找到工作代码。它甚至可能吗?我的意思是,其他网站使用相同的页面验证并提交给第三方数据库吗?

如果需要,我可以提供更多代码,但问题似乎就在这里。如果我不尝试更改返回,Captcha验证正常,'if(r.error == 0)'代码执行正常。我甚至添加了一个警告来显示“提交”的值,只是为了验证数据是否在函数之间传输。

我在这里结束了我的智慧。我将不胜感激任何帮助。

谢谢,

马特

完整代码(减去详细信息)如下:

<?php
session_start(); // this MUST be called prior to any output including whitespaces and line breaks!


$GLOBALS['DEBUG_MODE'] = 1;
// CHANGE TO 0 TO TURN OFF DEBUG MODE
// IN DEBUG MODE, ONLY THE CAPTCHA CODE IS VALIDATED, AND NO EMAIL IS SENT
// EMAIL is edited out for school use

// Process the form, if it was submitted (Original Code called process_si_contact_form())
process_si_zoho1();

?>
<html>
<head>

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/prototype/1.7.0.0/prototype.js"></script>


<script type="text/javascript">
//variables not part of original code
    function reloadCaptcha()
    {
    //original code ElementId labled 'captcha_code'
        document.getElementById('captcha').src = '/securimage_show.php?sid=' + Math.random();
    }

    var r, Submit;
function processForm()
{
    new Ajax.Request('<?php echo $_SERVER['PHP_SELF'] ?>', {
        method: 'post',
        //Original code did not state 'zoho1'
       parameters: $('zoho1').serialize(),
        onSuccess: function(transport) {
        //Re-edited for school use. Not original code
            try {
                r = transport.responseText.evalJSON();
                Submit = r.submit;

                if (r.error == 0) {
                alert('Congrats!');
                reloadCaptcha();


                } else {

                    alert("There was an error with your submission.\n\n" + r.message);

                }
            } catch(ex) {

                alert("There was an error parsing the json");

            }

        },
        onFailure: function(err) {

            alert("Ajax request failed");
        }

    });
return false;
}
}
</script>
</head>
<body>
    <form action="----------" id="zoho1" method="POST" name="leadForm" onsubmit="return processForm()">
        <input name="----------" type="hidden" value="----------" />
        <input name="----------" type="hidden" value="----------" />
        <input name="----------" type="hidden" value="----------" />
        <input name="----------" type="hidden" value="----------" />
        <input name="----------" type="hidden" value="----------" />
        <input name="----------" type="hidden" value="----------" />
        <input type="hidden" name="do" value="contact" /><br />
        <p>
            <label for="First Name">First Name</label><br />
                <input class="required" maxlength="40" name="First Name" type="text" /></p>
        <p>
            <label for="Last Name">Last Name</label><br />
                <input class="required" maxlength="80" name="Last Name" type="text" /></p>
        <p>
            <label email="" for="">Email</label><br />
                <input class="required validate-email" maxlength="100" name="Email" type="text" /></p>
        <p>
            <label for="Phone">Main Phone</label><br />
                <input class="required" maxlength="30" name="Phone" type="text" /></p>
        <p>
            <label for="Mobile">Mobile Phone</label><br />
                <input maxlength="30" name="Mobile" type="text" /></p>
        <p>
            <label for="State">State</label><br />
                <select class="required validate-selection" name="State"><option selected="selected" value="-None-">-None-</option><option value="AL">AL</option><option value="AK">AK</option><option value="AZ">AZ</option><option value="AR">AR</option><option value="CA">CA</option><option value="CO">CO</option><option value="CT">CT</option><option value="DE">DE</option><option value="DC">DC</option><option value="FL">FL</option><option value="HI">HI</option><option value="ID">ID</option><option value="IL">IL</option><option value="IN">IN</option><option value="IA">IA</option><option value="KS">KS</option><option value="KY">KY</option><option value="LA">LA</option><option value="ME">ME</option><option value="MD">MD</option><option value="MA">MA</option><option value="MI">MI</option><option value="MN">MN</option><option value="MS">MS</option><option value="MO">MO</option><option value="MT">MT</option><option value="NE">NE</option><option value="NV">NV</option><option value="NH">NH</option><option value="NJ">NJ</option><option value="NM">NM</option><option value="NY">NY</option><option value="NC">NC</option><option value="ND">ND</option><option value="OH">OH</option><option value="OK">OK</option><option value="OR">OR</option><option value="PA">PA</option><option value="RI">RI</option><option value="SC">SC</option><option value="SD">SD</option><option value="TN">TN</option><option value="TX">TX</option><option value="UT">UT</option><option value="VT">VT</option><option value="VA">VA</option><option value="WA">WA</option><option value="WV">WV</option><option value="WI">WI</option><option value="WY">WY</option><option value="GA">GA</option></select></p>
<!--<div><label for="Mailing Zip">Mailing Zip</label><br /><input type="text" maxlength="30" name="Mailing Zip" /></div>--><!--<div><label for="Mailing Country">Mailing Country</label><br /><input type="text" maxlength="30" name="Mailing Country" /></div>-->
        <p>
            <label for="----------">----------</label><br />
                <select class="required validate-selection" name="----------"><option selected="selected" value="-None-">-None-</option><option value="----------">----------</option><option value="----------">----------</option><option value="----------">----------</option><option value="----------">----------</option><option value="----------">----------</option><option value="----------">----------</option><option value="----------">----------</option><option value="----------">----------</option></select></p>
        <p>
            <label for="-------">----------</label><br />
                <select class="required validate-selection" name="-------"><option selected="selected" value="-None-">-None-</option><option value="----------">----------</option><option value="----------">----------</option><option value="----------">----------</option><option value="----------">----------</option><option value="----------">----------</option><option value="----------">----------</option></select></p>
        <p>
            <label for="-------">------------</label><br />
                <select class="required validate-selection" name="-------"><option selected="selected" value="-None-">-None-</option><option value="----------">----------</option><option value="----------">----------</option><option value="----------">----------</option><option value="---------">-----------</option></select></p>
        <p>
            <label for="-------">Intended Degree</label><br />
                <select class="required validate-selection" name="-------"><option selected="selected" value="-None-">-None-</option><option value="--------------">-------------</option><option value="-------------">-------------</option><option value="-------------">--------------</option></select></p>
        <p>
            <label for="-------">How did you hear about TTU?</label><br />
                <textarea class="required" height="250" maxlength="1000" name="-------" width="250"></textarea></p>
        <p>
            <label for="Description">Comments</label><br />
                <textarea height="250" maxlength="1000" name="Description" width="250"></textarea></p>
                    <img id="captcha" src="/securimage_show.php" alt="CAPTCHA IMAGE" />
                    <input type="text" id="enterVerify" name="captcha_code" size="10" maxlength="6" />
                    <input type="button" id="reload" name="Reload" value="Reload" onClick="reloadCaptcha()">
                <input class="form-button" name="save" type="submit" value="Submit" />
    </form>
</body>
</html>
<?php
//Original code process called 'process_si_contact_form())
function process_si_zoho1()
{
if ($_SERVER['REQUEST_METHOD'] == 'POST' && @$_POST['do'] == 'contact') {
    // if the form has been submitted

    foreach($_POST as $key => $value) {
        if (!is_array($key)) {
            // sanitize the input data
            if ($key != '-------') $value = strip_tags($value);
            $_POST[$key] = htmlspecialchars(stripslashes(trim($value)));
        }
    }

    $captcha = $_POST['captcha_code']; // the user's entry for the captcha code

    $errors = array();  // initialize empty error array


    if (sizeof($errors) == 0) {
        require_once dirname(__FILE__) . '/securimage.php';
        $securimage = new Securimage();

        if ($securimage->check($captcha) == false) {
            $errors['captcha_error'] = 'Incorrect security code entered';

        }
    }

   if (sizeof($errors) == 0) {
        // no errors, send the form
       //Edited out mail function from original code

//Changed JSON return array on successful validation to send new variable '$Submit' via serialized $entry
        $Submit = true;
        $entry = array('error' => 0, 'submit' => $Submit);
        die(json_encode($entry));
    } else {
        $errmsg = $captcha_error;
        foreach($errors as $key => $error) {
            // set up error messages to display with each field
            $errmsg .= " - {$error}\n";
            $Submit = false;
        }
//Added $Submit to the return array
        $return = array('error' => 1, 'message' => $errmsg, 'submit' => $Submit);
        die(json_encode($return));
    }


} // POST
} // function process_si_zoho1()


?>

2 个答案:

答案 0 :(得分:0)

<?php 

if( isset( $_POST['captcha'] ))
{
    $a = array("error"=>0);
    print json_encode( $a );
    exit();
}
?>

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/prototype/1.7.1.0/prototype.js" ></script>
</head>
<body onload="processForm()">




<form  id="formtest"  action="" method="POST">
<input type="text" name="captcha" value="1vfvrfr">
</form>

<script>

var r, Submit;
function reloadCaptcha(){}
function processForm()
    {
        new Ajax.Request('<?php echo $_SERVER['PHP_SELF'] ?>', {
            method: 'post',
            //Original code did not state 'zoho1'
           parameters: $('formtest').serialize(),
            onSuccess: function(transport) {
            //Re-edited for school use. Not original code
                try {
                    r = transport.responseText.evalJSON();
                    Submit = r.submit

                    if (r.error == 0) {
                    alert('Congrats!');
                    reloadCaptcha();


                    } else {

                        alert("There was an error with your submission.\n\n" + r.message);

                    }
                } catch(ex) {

                    alert("There was an error parsing the json");

                }

            },
            onFailure: function(err) {

                alert("Ajax request failed");
            }

        });
    return Submit;
    }

</script>
</body>
</html>

答案 1 :(得分:0)

感谢所有帮助。我做了一些更多的研究,问题出在JavaScript(我经验最少的代码部分)。我只是添加到:

if (r.error == 0)
document.forms['formname'].submit();

感谢帮帮!我肯定会再次使用这个论坛!