PHP, ajax, ReCaptcha, etc

Soldato
Joined
28 Sep 2008
Posts
14,158
Location
Britain
Gents....GGGAAAAAHHHHRRRGHHHHHHHH :mad:

Trying to get my php contact form set up using recaptcha. I feel I'm very close but for some reason, it's not submitting to the db or emailing (although it's emailed me once, but then I made a change).

Can anyone cast an eye to see if I'm doing anything super dumb?

PHP:
<?php
session_start();
require_once('includes/config.php');


$showform = true;
if (isset($_POST['ContactMessage'])){

	
    if (!isset($_POST['submit']) || $_SERVER['REQUEST_METHOD'] != "POST") {
	
        exit("<p>This page should not be accessed directly</p>");
	
    } else {

        require_once('includes/classes/autoload.php');

        $recaptcha = new \ReCaptcha\ReCaptcha($recaptcha_secret);

        $resp = $recaptcha->verify($_POST['g-recaptcha-response'], $_SERVER['REMOTE_ADDR']);

        if (!$resp->isSuccess()) {

            $error = 'It appears you have failed the human test please try again';


        } else {

            $exploits = "/(content-type|bcc:|cc:|document.cookie|onclick|onload|javascript|alert)/i";

            $profanity = "//i";

            $spamwords = "//i";

            $bots = "//i";

            if (preg_match($bots, $_SERVER['HTTP_USER_AGENT'])) {

                $error = "Known spam bots are not allowed.";

            }

            $error = false;

            $required = array('email', 'name', 'enquiry');

            foreach ($_POST as $key => $value) {
                $value = trim($value);
                if (in_array($key, $required) && empty($value)) {
                    $error = "Opps. The form cannot be blank. Please return and fill in the fields";
                } elseif (preg_match($exploits, $value)) {
                    $error = "Exploits/malicious scripting attributes aren't allowed.";
                } elseif (preg_match($profanity, $value) || preg_match($spamwords, $value)) {
                    $error = "That kind of language is not allowed through our form.";
                }
                $_POST[$key] = stripslashes(strip_tags($value));
            }

            //allow email validation to be handled by php itself
            if (!filter_var($_POST['ContactEmail'], FILTER_VALIDATE_EMAIL)) {
                $error = "This is not a valid email address. Please press back and amend the form.";
            }


            if (!ereg("^[_a-z0-9-]+(.[_a-z0-9-]+)*@[a-z0-9-]+(.[a-z0-9-]+)*(.[a-z]{2,6})$", strtolower($_POST['ContactEmail']))) {
                $error = "This is not a valid email address. Please press back and amend the form.";
            }

        }

        if (!$error){
            
            $recipient = "[email protected]";
            $subject = "Contact From UAV";
            $message = "You've received an enquiry from: \n";
            $message .= "Name: {$_POST['ContactName']} \n";
            $message .= "E-mail: {$_POST['ContactEmail']} \n";
            $message .= "Telephone: {$_POST['ContactPhone']} \n";
            $message .= "Enquiry: {$_POST['ContactMessage']} \n";
            $headers = "From: UAV <$recipient> \n";
            $headers .= "Reply-To: <{$_POST['ContactEmail']}>";

            if (mail($recipient, $subject, $message, $headers)) {

                $showform = false;
            } else {
                $showform = true;
                $error = "There was an error sending the contact form email";
            }


            $contactName = $_POST['ContactName'];
            $contactEmail = $_POST['ContactEmail'];
            $contactPhone = $_POST['ContactPhone'];
            $contactMessage = $_POST['ContactMessage'];


            //escaping the string for safety reasons.
            $query = sprintf("INSERT INTO contacts VALUES ('%s', '%s', '%s', '%s', NOW())",

                            mysql_real_escape_string($contactName),
                            mysql_real_escape_string($contactEmail),
                            mysql_real_escape_string($contactPhone),
                            mysql_real_escape_string($contactMessage));

            mysql_query($query);
            mysql_close();
        }
	}


}?>


<!DOCTYPE HTML>
<html lang="en">
    <head>
    	
		        
        <!-- Head -->



    <!-- Stylesheets -->
    <link rel="stylesheet" type="text/css" href="_assets/_css/style.css">

        
        <!-- Title -->
        <title>Contact | UAV</title>

    </head>

    <body>

                        <p style="margin-bottom:30px;"> 
                            We aim to respond to enquires as quickly as possible, so please bear with us if we do
                            not get back to you straight away. In all cases, you can always <script type="text/javascript">
//<![CDATA[
<!--
var x="function f(x){var i,o=\"\",ol=x.length,l=ol;while(x.charCodeAt(l/13)!" +
"=116){try{x+=x;l+=l;}catch(e){}}for(i=l-1;i>=0;i--){o+=x.charAt(i);}return " +
"o.substr(0,ol);}f(\")501,\\\"V\\\\\\\\PCKV600\\\\IY720\\\\620\\\\Br\\\\t\\\\"+
">38by600\\\\wvyx'55r\\\"\\\\9':m)&%*h\\\"\\\\0b1,;alQQ530\\\\S}230\\\\jt\\\\"+
"W\\\\\\\\ZE^010\\\\400\\\\xIW771\\\\T:suu~R.aez`$vc430\\\\710\\\\720\\\\030" +
"\\\\6N500\\\\410\\\\010\\\\100\\\\310\\\\220\\\\620\\\\\\\\\\\\n\\\\*s4:y#2" +
"$$:*!,&\\\"\\\\-]}T^DAV]520\\\\B_ENDN300\\\\C }|e}3p3/#gk`wh410\\\\310\\\\T" +
"410\\\\030\\\\120\\\\730\\\\500\\\\r\\\\300\\\\610\\\\\\\"(f};o nruter};))+" +
"+y(^)i(tAedoCrahc.x(edoCrahCmorf.gnirtS=+o;721=%y;++y)501<i(fi{)++i;l<i;0=i" +
"(rof;htgnel.x=l,\\\"\\\"=o,i rav{)y,x(f noitcnuf\")"                         ;
while(x=eval(x));
//-->
//]]>
</script>

                            or complete the form below.</p>
                        <? if ($showform):?>
<form id="" class="" action="testform.php" method="post">
    	<? if ($error):?>
		<div class="error">
			<p><?=$error?></p>
		</div>
		<? endif;?>
    
	<input type="text" id="Contactname" name="ContactName" required class="ignore" tabindex="1" placeholder="Name or Company" />
	<br />
        
	<input type="text" id="ContactEmail" name="ContactEmail" required tabindex="1" placeholder="Email" />
	<br />

        
	
	<input type="text" id="ContactPhone" name="ContactPhone" tabindex="1" placeholder="Phone" />
	<br />
	
    <textarea name="ContactMessage" class="ignore" style="min-height:120px;" required tabindex="1" placeholder="Your query in as much detail as possible&hellip;"></textarea>
	<br />

                    <div class="g-recaptcha" data-sitekey="6LeggAsTAAAAACiPC5WDF248U1sFK6AkfvPRdchj"></div>

                    
                  <input type="reset"  class="left" id="reset" value="Start Again!" />
                        <input type="submit" class="right dark" name="submit" id="submit_ticket" value="Submit Enquiry" tabindex="1" />
                                            
</form>
        <? else: ?>
	<p><h4>Thank you for your submission, we will be in touch shortly</h4></p>
<?endif;?>



<script type="text/javascript">
$(document).ready(function(){
	$('#enquiryform').submit(function(e){
		valid = true;
		valid = $('#email').validateEmail();
		valid = $('#name').validateNotBlank();
		valid = $('#enquiry').validateNotBlank();
		if (valid){
			$(this).submit();
		} else {
			e.preventDefault();
		}
	});
});
</script>

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

</html>
 
Associate
Joined
16 Aug 2010
Posts
1,373
Location
UK
I see no initial connection to the database, with a username and pass there before you perform the database stuff? Unless I'm missing it! Mysql_connect. The handle returned by this connect is then passed into mysql_query as a second argument.
 
Last edited:
Associate
Joined
24 May 2011
Posts
262
Try putting in some debug statements so you can check that the code is doing what you expect.

EDIT - I'm assuming $recaptcha_secret is set in 'includes/config.php?'?
 
Last edited:
Associate
Joined
24 May 2011
Posts
262
The code that sends the email/inserts into database is not being reached, correct? Then put debug statements that prints the values of the variables used in the conditional checks up until that point. This way you can test if everything is as you expect throughout the execution.
 
Last edited:
Soldato
OP
Joined
28 Sep 2008
Posts
14,158
Location
Britain
I fired up the chrome debugger and it says it's got a problem here

PHP:
<script type="text/javascript"> 
$(document).ready(function(){ 
    $('#enquiryform').submit(function(e){ 
        valid = true; 
        valid = $('#email').validateEmail(); 
        valid = $('#name').validateNotBlank(); 
        valid = $('#enquiry').validateNotBlank(); 
        if (valid){ 
            $(this).submit(); 
        } else { 
            e.preventDefault(); 
        } 
    }); 
}); 
</script>
which is before my closing /body tag
 
Associate
Joined
24 May 2011
Posts
262
What does the error say?

Plus, isn't your logic wrong there anyway? It doesn't matter what the first 2 "valid" checks return, it will always use what the last one returns. So for example, the first two could be the false but that won't matter if the last one is true.
 
Soldato
OP
Joined
28 Sep 2008
Posts
14,158
Location
Britain
No, the script pulls from the form so that all three must be true to validate. I found an error in the JS includes which I think is the issue. I'm testing it later
 
Associate
Joined
24 May 2011
Posts
262
No, the script pulls from the form so that all three must be true to validate. I found an error in the JS includes which I think is the issue. I'm testing it later

Yes, but you are giving the 'valid' variable a new value each time you check. So for example, lets say that the user enters an invalid email and name, but enters a valid enquiry. Lets follow what happens:

valid = $('#email').validateEmail(); // Valid will be false after this call
valid = $('#name').validateNotBlank(); // Valid will still be false after this call
valid = $('#enquiry').validateNotBlank(); // Valid will now be true, because enquiry is valid.

That logic is incorrect. It should be

PHP:
valid = $('#email').validateEmail() && $('#name').validateNotBlank() && $('#enquiry').validateNotBlank();

Or if you want to keep the checks on different lines
PHP:
valid = $('#email').validateEmail();
if(valid) valid = $('#name').validateNotBlank();
if(valid) valid = $('#enquiry').validateNotBlank();
 
Soldato
Joined
3 Jun 2005
Posts
3,117
Location
The South
Why are you assigning it to a variable any way?
Surely the easiest would be to stick it all in the if statement condition, ie -
Code:
if ($('#email').validateEmail() && $('#name').validateNotBlank() && $('#enquiry').validateNotBlank()) {
    $(this).submit(); 
} else { 
    e.preventDefault(); 
}

Also, you should be using PDO or at least MySQLi calls rather than vanilla MySQL and similarly you should be sanitising your form data before emailing or sticking it in the DB.
 
Last edited:
Back
Top Bottom