0

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>
Sverkel
  • 7
  • 6
  • 1
    If I'm reading your issue right, it looks like it's "not working" because you first test the captcha, then instantly redirect the user elsewhere before the rest of the process runs. – Jonnix Nov 17 '15 at 13:55
  • 1
    Hey! Welcome to StackOverflow. In general when you're posting a question try to remove unnecessary code to just leave the bare minimum of what's necessary tor repeat the problem. Give this a read: http://stackoverflow.com/help/mcve – Michael Nov 17 '15 at 13:56
  • @JonStirling that is right, but I just can't figure out how to correct the error? – Sverkel Nov 17 '15 at 14:09
  • Please provide a bare minimum code to recreate the issue. – Rajdeep Paul Nov 17 '15 at 14:10
  • @Sverkel By not redirecting and instead treating the recaptcha response as part of your form validation. – Jonnix Nov 17 '15 at 14:11
  • @JonStirling So your are telling me I need to place the reCaptcha in the validation.sj? – Sverkel Nov 17 '15 at 14:16
  • @RajdeepPaul I'm not sure what the bare minimum are? I look at the code and I can't see what I can take out without breaking something? – Sverkel Nov 17 '15 at 14:30
  • @Sverkel, Does recaptcha shows correctly on your page? – Rajdeep Paul Nov 17 '15 at 14:42

1 Answers1

0

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>
Rajdeep Paul
  • 16,887
  • 3
  • 18
  • 37
  • Thank you for doing all that work! I just got one problem, I can't seem to figure out where to put the code you provided? I can't get it to work? – Sverkel Nov 17 '15 at 19:02
  • Okay, I have tried replacing the code you said, but it still won't work. And what do you mean by this "you should do all your input validation and form processing here"? Shall I place all my validation code there from the .js file or? – Sverkel Nov 17 '15 at 19:42
  • JavaScript form validation and PHP form validation are very different. JavaScript validates form inputs on client side or browser side but PHP validates form inputs on server side. Read this answer to know about PHP input validation and form processing, [http://stackoverflow.com/a/33650667/5517143](http://stackoverflow.com/a/33650667/5517143) – Rajdeep Paul Nov 17 '15 at 20:16
  • Thanks but that don't help me at all :( Could you tell me exactly where your code shall go please? – Sverkel Nov 17 '15 at 20:23
  • I gotten to the point where if I press Send message the recaptcha validation tells me it's not activated and my other validation is working, but I can without trouble still just fill in all the fields and then the messages will be sent and only when the message is sent I get the message that the recaptcha was not activated? – Sverkel Nov 18 '15 at 07:48
  • It's impossible for me to debug your code without even seeing it. Kindly give the edited version(whatever you tried) of your code. – Rajdeep Paul Nov 18 '15 at 13:13
  • I have made edit to the original post to show what I did. Hope you can use it. – Sverkel Nov 18 '15 at 13:28
  • Make sure you have entered correct public and private keys for recaptcha. And you said that you're able to send mails irrespective of the recaptcha result is because of the fact that you're doing recaptcha validation and form validation in two different blocks. Follow this process, first validate recaptcha. If recaptcha validation is successful then only process the form inputs and send mail. I have checked the recaptcha using my own public and private keys, and it's working fine. – Rajdeep Paul Nov 18 '15 at 14:31
  • The codes are correct. I understand what you are saying, but I can't figure out how to do it? My reCaptcha validation is before the form validation in the contact.php file, but I wonder if the reCaptcha validation must be a part of the form validation that is in the file validation.js? – Sverkel Nov 18 '15 at 14:40
  • validation.js? How did this validation.js come to picture? You didn't even mention what's in there. You can do everything I said in the last comment without even touching validation.js. I believe validation.js is for validating form inputs on browser side, correct? – Rajdeep Paul Nov 18 '15 at 15:52
  • Yes that is correct about the validation.js, I have been looking into what you said but I just can't figure out how to do it :( – Sverkel Nov 18 '15 at 16:14
  • I've updated my answer. Please read the **re-edited** section of my answer. – Rajdeep Paul Nov 18 '15 at 18:39
  • You are AWESOME! Works! :D One last thing. When I get the mail it includes a lot of random code that looks to be related to the reCaptcha? Any advice on how to remove that? g-recaptcha-response: 03AHJ_VutSp6jxdQwFW4YhBm6CntzIEEdgbWtjdgoSeIaHasFE- KpkFUhGy3rashFrsRkKfogLT14FAm_WCd_LlSLQVpAe-_XgvRrQIKrTaygLBfJ5J8O60MnLK6l9OUgh_nAkFFq19KlCguNXqfuppfq1MtnjX13JoZN5BAez6azFcpNKe810E24jboem2_IRS_urAb_WebNcFTI5xW-ZCBfd5Ev5esOgsODZOZqs1Hvyi4XppKAxSLSgN6OAe9hc7JrYkyYX6kEuVgXS6lVaaWq2SqXTg2kjSxkfeiHLEtoFsUN89B1y5dWhWzOdRBxp0kNupgLf2FQU -- And a lot mere of the same... – Sverkel Nov 18 '15 at 18:59
  • Oh yes, that's because `g-recaptcha-response` is also sent as form input(along with other input data) when you submit the form. You can catch and display its content using superglobal `$_POST`, like this, `echo $_POST['g-recaptcha-response'];`. I've updated the code. Refer that `if` clause inside `foreach` loop before the `mail()` function. – Rajdeep Paul Nov 18 '15 at 19:42
  • Thank you so much! You have saved my a.. BIG time! :D I will accept your answer right away! :D – Sverkel Nov 18 '15 at 19:48