reCaptcha breaks other validation?

2019-06-13 07:30发布

问题:

I'm about to make a contact form with reCaptcha but when I apply the reCaptcha and make validation on that, my other validation on the forms won't work and I just can't seem to find out why? I have tried other ways to make the recaptcha validate but nothing works?

OLD CODE START:

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

$url = 'https://www.google.com/recaptcha/api/siteverify';
$privatekey = "MY SECRET CODE GOES HERE";

$response = file_get_contents($url."?             secret=".$privatekey."&response=".$_POST['g-recaptcha-response']."&remoteip=".$_SERVER['REMOTE_ADDR']);
$data = json_decode($response);

if(isset($data->success) AND $data->success==true) {

header('Location:contact.php?CaptchaPass=True');


}else{

header('Location:contact.php?CaptchaFail=True');



}

}


?>

OLD CODE END ^

^ CODE HAS BEEN REPLACED WITH:

<?php

$valid_recaptcha = false;
if(isset($_POST['submit'])){
$url = 'https://www.google.com/recaptcha/api/siteverify';
$privatekey = "MY SECRET CODE GOES HERE";
$response = file_get_contents($url."?secret=".$privatekey."&response=".$_POST['g-recaptcha-response']."&remoteip=".$_SERVER['REMOTE_ADDR']);
$data = json_decode($response);
if(isset($data->success) AND $data->success==true) {
    $valid_recaptcha = true;
}

if($valid_recaptcha){


}else{

}
}

?>

NEW CODE END ^

<?php

// Set email variables

$email_to = 'MY MAIL GOES HERE';

$email_subject = 'Formular: Kontakt os';



// Set required fields

$required_fields = array('navn', 'postnr', 'by', 'email', 'telefon',     'besked');



// set error messages

$error_messages = array(

'navn' => 'Skriv venligst dit navn',

'postnr' => 'Skriv venligst et gyldigt post nr',

'by' => 'Skriv venligst et gyldigt bynavn',

'email' => 'Skriv venligst en gyldig e-mail adresse',

'telefon' => 'Skriv venligst et gyldigt telefon nr',

'besked' => 'Skriv venligst en besked'

);



// Set form status

$form_complete = FALSE;



// configure validation array

$validation = array();



// check form submittal

if(!empty($_POST)) {

// Sanitise POST array

foreach($_POST as $key => $value) $_POST[$key] =     remove_email_injection(trim($value));



// Loop into required fields and make sure they match our needs

foreach($required_fields as $field) {       

    // the field has been submitted?

    if(!array_key_exists($field, $_POST)) array_push($validation, $field);



    // check there is information in the field?

    if($_POST[$field] == '') array_push($validation, $field);



    // validate the email address supplied

    if($field == 'email') if(!validate_email_address($_POST[$field]))     array_push($validation, $field);

}



// basic validation result

if(count($validation) == 0) {

    // Prepare our content string

    $email_content = 'Ny besked fra kontaktformular: ' . "\n\n";



    // simple email content

    foreach($_POST as $key => $value) {

        if($key != 'submit') $email_content .= $key . ': ' . $value . "\n";

    }



    // if validation passed ok then send the email

    mail($email_to, $email_subject, $email_content);



    // Update form switch

    $form_complete = TRUE;

  }

}



function validate_email_address($email = FALSE) {

return (preg_match('/^[^@\s]+@([-a-z0-9]+\.)+[a-z]{2,}$/i', $email))? TRUE :     FALSE;

}



function remove_email_injection($field = FALSE) {

return (str_ireplace(array("\r", "\n", "%0a", "%0d", "Content-Type:",     "bcc:","to:","cc:"), '', $field));

}



?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Kontakt os</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link href="css/contactform.css" rel="stylesheet" type="text/css" />
<script type="text/javascript"    src="https://ajax.googleapis.com/ajax/libs/mootools/1.3.0/mootools-yui- compressed.js"></script>
<script type="text/javascript" src="validation/validation.js"></script>

<script type="text/javascript">

    var navnError = '<?php echo $error_messages['navn']; ?>';

    var postnrError = '<?php echo $error_messages['postnr']; ?>';

    var byError = '<?php echo $error_messages['by']; ?>';

    var emailError = '<?php echo $error_messages['email']; ?>';

    var telefonError = '<?php echo $error_messages['telefon']; ?>';

    var beskedError = '<?php echo $error_messages['besked']; ?>';

</script>
<script src='https://www.google.com/recaptcha/api.js'></script>
</head>
<body>

<div id="formWrap">
<h3>Kontakt os</h3>

OLD CODE START:

<?php if(isset($_GET['CaptchaPass'])){ ?>
<div class="detail" style="margin-left: 200px;" align="center">Din besked er   nu sendt</div><br />
<?php } ?> 
<?php if(isset($_GET['CaptchaFail'])){ ?>
<div class="detail" style="margin-left: 200px;" align="center">reCaptcha   fejlede, prøv venligst igen</div><br />
<?php } ?>

OLD CODE END ^

^ CODE HAS BEEN REPLACED WITH:

<?php
if(isset($_POST['submit'])){
    if($valid_recaptcha){
        ?>
        <?php
    }else{
        ?>
        <div class="detail" style="margin-left: 200px;" align="center">Kontrol fejlede, prøv venligst igen</div><br />
        <?php
    }
}
?>

NEW CODE END ^

REST OF THE CODE HAS NOT BEEN EDITED.

<div id="form">
<?php if($form_complete === FALSE): ?>

<form action="contact.php" method="post" id="comments_form">
<div class="row">
<div class="label">Navn</div><!-- slut .label -->
<div class="input">
<input type="text" id="navn" class="detail" name="navn" value="<?php echo     isset($_POST['navn'])? $_POST['navn'] : ''; ?>" /><?php if(in_array('navn',    $validation)): ?><span class="error"><?php echo $error_messages['navn']; ?>        </span><?php endif; ?>
</div><!-- slut .input -->
</div><!-- slut .row -->

<div class="row">
<div class="label">Post nr.</div><!-- slut .label -->
<div class="input">
<input type="text" id="postnr" class="detail" name="postnr" value="<?php     echo isset($_POST['postnr'])? $_POST['postnr'] : ''; ?>" /><?php  if(in_array('postnr', $validation)): ?><span class="error"><?php echo  $error_messages['postnr']; ?></span><?php endif; ?>
</div><!-- slut .input -->
</div><!-- slut .row -->

<div class="row">
<div class="label">By</div><!-- slut .label -->
<div class="input">
<input type="text" id="by" class="detail" name="by" value="<?php echo  isset($_POST['by'])? $_POST['by'] : ''; ?>" /><?php if(in_array('by',  $validation)): ?><span class="error"><?php echo $error_messages['by']; ?></span>   <?php endif; ?>
</div><!-- slut .input -->
</div><!-- slut .row -->

<div class="row">
<div class="label">E-mail adresse</div><!-- slut .label -->
<div class="input">
<input type="text" id="email" class="detail" name="email" value="<?php echo   isset($_POST['email'])? $_POST['email'] : ''; ?>" /><?php if(in_array('email', $validation)): ?><span class="error"><?php echo $error_messages['email']; ?></span><?php endif; ?>
</div><!-- slut .input -->
</div><!-- slut .row -->

<div class="row">
<div class="label">Telefon</div><!-- slut .label -->
<div class="input">
<input type="text" id="telefon" class="detail" name="telefon" value="<?php echo isset($_POST['telefon'])? $_POST['telefon'] : ''; ?>" /><?php if(in_array('telefon', $validation)): ?><span class="error"><?php echo $error_messages['telefon']; ?></span><?php endif; ?>
</div><!-- slut .input -->
</div><!-- slut .row -->

<div class="row">
<div class="label">Besked</div><!-- slut .label -->
<div class="input">
<textarea id="comment" name="besked" class="mess"><?php echo  isset($_POST['besked'])? $_POST['besked'] : ''; ?>
</textarea><?php if(in_array('besked', $validation)): ?><span class="error">   <?php echo $error_messages['besked']; ?></span><?php endif; ?>
</div><!-- slut .input -->
</div><!-- slut .row -->
<br /><div class="g-recaptcha" data- sitekey="6LfEZw0TAAAAAEsi1Gba_D98TgEIN3tw0YUfeB63" style="margin-left: 200px;"> </div>
<div class="submit">
<input type="submit" id="submit" name="submit" value="Send besked" /><br /> <br />
</form>
</div><!-- .submit -->
<?php else: ?>

<p style="font-size:25px; font-family:Arial, sans-serif; margin-   left:25px;">Tak for din besked</p>

<script type="text/javascript">
setTimeout('ourRedirect()',5000)
function ourRedirect(){
location.href='http://www.apple.dk'
}

</script>

<?php endif; ?>


</div><!-- slut #form -->
</div><!-- slut formWrap -->



</body>
</html>

回答1:

Problem

Your header inside if(isset($_POST['submit'])){ ... } is causing this error. header() is used to send a raw HTTP header to the browser. Whenever browser requests a page to the server, before server responds, it first sends the headers i.e what browser can expect next and browser can render itself accordingly, and then server sends the actual page.

if(isset($_POST['submit'])){
    $url = 'https://www.google.com/recaptcha/api/siteverify';
    $privatekey = "MY SECRET CODE GOES HERE";
    $response = file_get_contents($url."?secret=".$privatekey."&response=".$_POST['g-recaptcha-response']."&remoteip=".$_SERVER['REMOTE_ADDR']);
    $data = json_decode($response);
    if(isset($data->success) AND $data->success==true) {
    header('Location:contact.php?CaptchaPass=True');    // this is causing the error
    }else{
    header('Location:contact.php?CaptchaFail=True');    // this might cause the same problem in near future
    }
}

Solution

Instead of validating recaptcha using superglobal $_GET, you can use a simple boolean variable to validate it.

$valid_recaptcha = false;
if(isset($_POST['submit'])){
    $url = 'https://www.google.com/recaptcha/api/siteverify';
    $privatekey = "MY SECRET CODE GOES HERE";
    $response = file_get_contents($url."?secret=".$privatekey."&response=".$_POST['g-recaptcha-response']."&remoteip=".$_SERVER['REMOTE_ADDR']);
    $data = json_decode($response);
    if(isset($data->success) AND $data->success==true) {
        $valid_recaptcha = true;
    }

    if($valid_recaptcha){
        // you should do all your input validation and form processing here

    }else{
        // user has entered wrong recaptcha
    }
}

And then you can render your page accordingly.

Edited:

Instead of this:

<?php if(isset($_GET['CaptchaPass'])){ ?>
<div class="detail" style="margin-left: 200px;" align="center">Din besked er    nu sendt</div><br />
<?php } ?> 
<?php if(isset($_GET['CaptchaFail'])){ ?>
<div class="detail" style="margin-left: 200px;" align="center">reCaptcha   fejlede, prøv venligst igen</div><br />
<?php } ?>

you can do something like this to display the message:

<?php
    if(isset($_POST['submit'])){
        if($valid_recaptcha){
            ?>
            <div class="detail" style="margin-left: 200px;" align="center">Din besked ernu sendt</div><br />
            <?php
        }else{
            ?>
            <div class="detail" style="margin-left: 200px;" align="center">reCaptcha fejlede, prøv venligst igen</div><br />
            <?php
        }
    }
?>

Re-edited:

I've typed and tested the entire code on my local machine, and it's working just as you had expected. I didn't touch validation.js because I think you can do browser side validation later on your own. Replace the $private_key with your secret private key, add a valid email address to $email_to and run the code on your system.

<?php
/*
* I don't know Danish language, but somehow I managed to understand your input field names.
* Thanks to google translate. :)
*/

function validate_email_address($email = false) {
    return (preg_match('/^[^@\s]+@([-a-z0-9]+\.)+[a-z]{2,}$/i', $email))? true : false;
}

function remove_email_injection($field = false) {
    return (str_ireplace(array("\r", "\n", "%0a", "%0d", "Content-Type:", "bcc:","to:","cc:"), '', $field));
}

// Set email variables
$email_to = 'MY MAIL GOES HERE';
$email_subject = 'Formular: Kontakt os';

// Set required fields
$required_fields = array('navn', 'postnr', 'by', 'email', 'telefon',     'besked');

// set error messages
$error_messages = array(
    'navn' => 'Skriv venligst dit navn',
    'postnr' => 'Skriv venligst et gyldigt post nr',
    'by' => 'Skriv venligst et gyldigt bynavn',
    'email' => 'Skriv venligst en gyldig e-mail adresse',
    'telefon' => 'Skriv venligst et gyldigt telefon nr',
    'besked' => 'Skriv venligst en besked'
);

// Set form status
$form_complete = FALSE;

// configure validation array
$validation = array();

// boolean variable to validate recaptcha
$valid_recaptcha = false;

if(isset($_POST['submit'])){
    // First validate recaptcha

    $url = 'https://www.google.com/recaptcha/api/siteverify';
    $privatekey = "MY SECRET CODE GOES HERE";
    $response = file_get_contents($url."?secret=".$privatekey."&response=".$_POST['g-recaptcha-response']."&remoteip=".$_SERVER['REMOTE_ADDR']);
    $data = json_decode($response);
    if($data->success) {
        $valid_recaptcha = true;
    }

    if($valid_recaptcha){

        // now process your form here. sanitize and validate input fields

        // Sanitise POST array
        foreach($_POST as $key => $value){
            $_POST[$key] = remove_email_injection(trim($value));
        }

        // Loop into required fields and make sure they match our needs
        foreach($required_fields as $field) {       

            // the field has been submitted?
            if(!array_key_exists($field, $_POST)){
                array_push($validation, $field);
            }

            // check there is information in the field?
            if($_POST[$field] == ''){
                array_push($validation, $field);
            }

            // validate the email address supplied
            if($field == 'email'){
                if(!validate_email_address($_POST[$field])){
                    array_push($validation, $field);
                }
            }

        }

        // basic validation result
        if(count($validation) == 0) {

            // Prepare our content string
            $email_content = 'Ny besked fra kontaktformular: ' . "\n\n";

            // simple email content
            foreach($_POST as $key => $value){
                if($key != 'submit' && $key != 'g-recaptcha-response') $email_content .= $key . ': ' . $value . "\n";

            }

            // if validation passed ok then send the email
            mail($email_to, $email_subject, $email_content);

            // Update form switch
            $form_complete = TRUE;

        }

    }
}

?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
    <title>Kontakt os</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <link href="css/contactform.css" rel="stylesheet" type="text/css" />
    <!--<script type="text/javascript"    src="https://ajax.googleapis.com/ajax/libs/mootools/1.3.0/mootools-yui- compressed.js"></script>-->
    <!--<script type="text/javascript" src="validation/validation.js"></script>-->
    <script src='https://www.google.com/recaptcha/api.js'></script>
</head>

<body>
    <div id="formWrap">
    <h3>Kontakt os</h3>

    <?php
    if(isset($_POST['submit'])){
        if(!$valid_recaptcha){
            // error
            ?>
                <div class="detail" style="margin-left: 200px;" align="center">Kontrol fejlede, prøv venligst igen</div><br />
            <?php
        }
    }
    ?>

    <div id="form">
    <?php if($form_complete === FALSE): ?>
    <form action="contact.php" method="post" id="comments_form">
        <div class="row">
        <div class="label">Navn</div><!-- slut .label -->
        <div class="input">
        <input type="text" id="navn" class="detail" name="navn" value="<?php echo     isset($_POST['navn'])? $_POST['navn'] : ''; ?>" /><?php if(in_array('navn',    $validation)): ?><span class="error"><?php echo $error_messages['navn']; ?>        </span><?php endif; ?>
        </div><!-- slut .input -->
        </div><!-- slut .row -->

        <div class="row">
        <div class="label">Post nr.</div><!-- slut .label -->
        <div class="input">
        <input type="text" id="postnr" class="detail" name="postnr" value="<?php     echo isset($_POST['postnr'])? $_POST['postnr'] : ''; ?>" /><?php  if(in_array('postnr', $validation)): ?><span class="error"><?php echo  $error_messages['postnr']; ?></span><?php endif; ?>
        </div><!-- slut .input -->
        </div><!-- slut .row -->

        <div class="row">
        <div class="label">By</div><!-- slut .label -->
        <div class="input">
        <input type="text" id="by" class="detail" name="by" value="<?php echo  isset($_POST['by'])? $_POST['by'] : ''; ?>" /><?php if(in_array('by',  $validation)): ?><span class="error"><?php echo $error_messages['by']; ?></span>   <?php endif; ?>
        </div><!-- slut .input -->
        </div><!-- slut .row -->

        <div class="row">
        <div class="label">E-mail adresse</div><!-- slut .label -->
        <div class="input">
        <input type="text" id="email" class="detail" name="email" value="<?php echo   isset($_POST['email'])? $_POST['email'] : ''; ?>" /><?php if(in_array('email', $validation)): ?><span class="error"><?php echo $error_messages['email']; ?></span><?php endif; ?>
        </div><!-- slut .input -->
        </div><!-- slut .row -->

        <div class="row">
        <div class="label">Telefon</div><!-- slut .label -->
        <div class="input">
        <input type="text" id="telefon" class="detail" name="telefon" value="<?php echo isset($_POST['telefon'])? $_POST['telefon'] : ''; ?>" /><?php if(in_array('telefon', $validation)): ?><span class="error"><?php echo $error_messages['telefon']; ?></span><?php endif; ?>
        </div><!-- slut .input -->
        </div><!-- slut .row -->

        <div class="row">
        <div class="label">Besked</div><!-- slut .label -->
        <div class="input">
        <textarea id="comment" name="besked" class="mess"><?php echo  isset($_POST['besked'])? $_POST['besked'] : ''; ?>
        </textarea><?php if(in_array('besked', $validation)): ?><span class="error">   <?php echo $error_messages['besked']; ?></span><?php endif; ?>
        </div><!-- slut .input -->
        </div><!-- slut .row -->

        <br />
        <div class="g-recaptcha" data-sitekey="6LfEZw0TAAAAAEsi1Gba_D98TgEIN3tw0YUfeB63"></div>
        <div class="submit">
        <input type="submit" id="submit" name="submit" value="Send besked" /><br /> <br />
        </div><!-- .submit -->
    </form>
    <?php else: ?>

    <p style="font-size:25px; font-family:Arial, sans-serif; margin-left:25px;">Tak for din besked</p>

    <!--<script type="text/javascript">
        setTimeout('ourRedirect()',5000)
            function ourRedirect(){
            location.href='http://www.apple.dk'
        }
    </script>-->

    <?php endif; ?>

    </div><!-- slut #form -->
</div><!-- slut formWrap -->

</body>
</html>