5 Replies - 372 Views - Last Post: 16 October 2019 - 09:32 AM Rate Topic: -----

#1 holthaunt   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 38
  • Joined: 10-February 17

PHP ReCaptcha Showing Error on Page Load

Posted 13 October 2019 - 09:17 PM

Hello.

I am new to PHP, as in this is my first project that I have attempted to use PHP. I am trying to add a Google reCaptcha to a form on my website, because I am receiving bot emails from this form in the middle of the night. I have tried a number of different video and websites tutorials in order to do this. Each time I had issues getting this to work correctly, even thought I think I have followed the code in the tutorials. This is the first one that has come close to working correctly, except for this one issue, which is, the final else statement, to catch if the recaptcha is not successful due to not being checked(I believe), is displaying the error code when the page first loads. I can fill out the form and it is sent with a confirmation message. My question is what do I need to do to make the final else statement code not display until an unsuccessful attempt with the reCaptcha. Please keep answers as simple as possible since, again, I am very unfamiliar with PHP.

Thank you for any assistance!

Here is where you can see a test page displayed: https://holthaunt.co.../test_one_offs/

Here is the code:

<!DOCTYPE html>
<head>
	<title>Cartering Form</title>
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
	<script src="https://www.google.com/recaptcha/api.js" async="defer"></script>
	<style type="text/css">
		body
		{
			margin: 0;
		}    
		main
		{	
			display: flex;
			flex-direction: column;
			justify-content: space-between;
			width: 98%;
			margin: auto;
		}
		form
		{	display: flex;
			flex-direction: column;
			width: 100%;
			margin: auto;		
		}
		.line
		{
			display: flex;
			flex-direction: row;
			flex-wrap: nowrap;
			justify-content: space-around;
			width: 100%;
		}
		.line04, .line05
		{
			justify-content: flex-start;
			padding-left: 1em;
		}
		input
		{	width: 100%;
			height: 2em;
		}
		.line04 input
		{	
			display: flex;
			justify-content: flex-start;
			align-items: flex-start;
			width: 80%;
			height: 6em;
		}
		p
		{
			width: 45%;
		}
		.line04 p
		{
			width: 100%;
		}
		.line05
		{
			width: 100%;
		}
		.line05 input
		{
			background: #077A3D;
			color: white;
			height: 2em;
			margin: auto;
		}
		.phpMsg
		{
			width: 80%;
			height: 2em;
			padding-bottom: .1325em;
			padding-top: .1325em;
		}
		span
		{
			color: red;
		}
		.g-recaptcha
		{
			
		}
	</style>
</head>
<body>
 <!-- EMAIL VALIDATION -->
	<main>	
		<form action="<?= $_SERVER['PHP_SELF'] ?>" method="post">
			<div class="line line01">
				<p>
					<label>Name
						<input type="text" name="name" required placeholder="Your Name" required >
					</label> 
				</p>
				<p>
					<label>Email 
						<input type="email" name="email_address" placeholder="[email protected]" required>
					</label>
				</p>
			</div>
			<div class="line line02">
				<p>
					<label>Date of Event
						<input type="date" name="date">
					</label> 
				</p>
				<p>
					<label>Phone
						<input class="phone" type="tel" name="phone_num" placeholder="(555) 123-0000" required>
					</label>
				</p>
			</div>
			<div class="line line03">
				<p>
					<label>Number of People
						<input type="number" name="num_people">
					</label> 
				</p>
				<p>
					<label>Type of Event
						<input type="text" name="type_event">
					</label>
				</p>
			</div>
			<div class="line line04">
				<p>
					<label>Message
						<input type="text" name="message">
					</label>
				</p>
			</div>
			<div class="line line05">
				<p>
					<input type="Submit" value="Submit"/>
				</p>
			</div>
		</form>
		<div class="phpMsg">
			<?php
		      $secret = 'my code'; //intentionally omitted
		      $url = "https://www.google.com/recaptcha/api/siteverify?secret=$secret&response=".$_POST['g-recaptcha-response'];
		      $verify = json_decode(file_get_contents($url));

		      if ($verify->success) {
		        $to = "my email"; //intentionally omitted
		        $subject = "Cartering For My Event";
		        $message = "Name:  " . $_POST['name']. "\r\n";
		        $message .= "Email: " . $_POST['email_address']. "\r\n";
		        $message .= "Phone Number:  " . $_POST['phone_num']. "\r\n";
		        $message .= "Date of Event: " . $_POST['date']. "\r\n";
		        $message .= "Expected Number of People: " . $_POST['num_people']. "\r\n";
		        $message .= "Type of Event: " . $_POST['type_event']. "\r\n";
		        $message .= "Message: " . $_POST['message']. "\r\n";
		        if (@mail($to, $subject, $message)) {

		          echo "Your information has been submitted. Henry will contact you shortly to verify and help you plan your event.";
		        } 
		        else {
		          
		          echo "There has been an error. Please ensure you have completed all fields before submitting the form.";
		        }
		      } 
		      else {
		       
		       echo "<span>Error: Please make sure to click reCapthca to verify you are not a robot.</span>";
		      }
		    ?>
		</div>
    	<div class="g-recaptcha" data-sitekey="my code"></div> <!--intentionally omitted -->
	</main>
	<script type="text/javascript">
			$(document).ready(function()
			{
			/*** PHONE NUMBER FORMAT ***/
				$(".phone").keypress(function (e)
				{
					if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57))
					{
						return false;
					}
					var curchr = this.value.length;
					var curval = $(this).val();
					if (curchr == 3 && curval.indexOf("(") <= -1)
					{
						$(this).val("(" + curval + ")" + "-");
					}
					else if (curchr == 4 && curval.indexOf("(") > -1)
					{
						$(this).val(curval + ")-");
					}
					else if (curchr == 5 && curval.indexOf(")") > -1)
					{
							$this.val(curval + "-");
					}
					else if (curchr == 9)
					{
						$(this).val(curval + "-");
						$(this).attr('maxlength', '14');
					}
				});
			});
	</script>
<body>


Is This A Good Question/Topic? 0
  • +

Replies To: PHP ReCaptcha Showing Error on Page Load

#2 ArtificialSoldier   User is offline

  • D.I.C Lover
  • member icon

Reputation: 2494
  • View blog
  • Posts: 7,551
  • Joined: 15-January 14

Re: PHP ReCaptcha Showing Error on Page Load

Posted 14 October 2019 - 08:28 AM

The simple answer is that you need to only run the PHP code if the form was actually submitted. A couple ways to do that would be to check for the presence of the form data inside $_POST, or to check if the page was requested using the post method at all. If you want to check if it was a post request, you can use the $_SERVER array to get information about the current request:

https://www.php.net/...bles.server.php

e.g.:

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
  // process the form
}

Was This Post Helpful? 0
  • +
  • -

#3 holthaunt   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 38
  • Joined: 10-February 17

Re: PHP ReCaptcha Showing Error on Page Load

Posted 14 October 2019 - 07:05 PM

Thanks ArtificialSoldier. I read the information in the link you sent, most is still foreign to me. I have spent part of the day doing more research. I am wondering where this goes and does is replace the
if($verify->success)
or do I include it with this code, with a
&&
. As I understand it the
if($verify->success)
is what checks if the reCaptcha is checked with success.

It weird, that the tutorials I tried didn't have anything like the e.g., ArtificialSoldier provided, but their's seem to work fine. I may have had errors in my code, since I do not copy and paste code, but type it out myself. I tried a few different examples, but each had it's own issue. The code in my first post is a hodgepodge of the different tutorials I tried, and it the first that actually worked, with the exception of my current issue.

Any one who can shed light on if I am heading the correct direction with this would help tremendously. Thank you.

This post has been edited by holthaunt: 14 October 2019 - 07:06 PM

Was This Post Helpful? 0
  • +
  • -

#4 ArtificialSoldier   User is offline

  • D.I.C Lover
  • member icon

Reputation: 2494
  • View blog
  • Posts: 7,551
  • Joined: 15-January 14

Re: PHP ReCaptcha Showing Error on Page Load

Posted 15 October 2019 - 09:19 AM

It doesn't replace anything, you need to put all of your PHP code inside that if statement so that you only run the code if the form is submitted.

If you search for "PHP check if form is submitted" you'll see similar techniques. The examples you're looking at are probably standalone pages that only process the form instead of a single page that both displays and processes like you have.
Was This Post Helpful? 0
  • +
  • -

#5 holthaunt   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 38
  • Joined: 10-February 17

Re: PHP ReCaptcha Showing Error on Page Load

Posted 15 October 2019 - 08:01 PM

ArtificialSoldier,thanks that worked for the error showing on load, but now I am faced with the same issue I have had with all previous attempts. When the form is filled, the reCaptcha is checked, and submit button is clicked I get an the error saying my reCaptcha is has not been checked. At least the previous version before making your suggested changes I could submit a form successfully. I'll open a new thread for my new issue, but will keep this going in case you have any ideas.

I have contacted my hosting company to check if it could be a server issue on their side. This was their reply:

"I'm really sorry, since it is the scripting related website we do not have much information regarding this, I have checked with our senior admins and they have informed that the reCaptcha added in the website are incorrect. It needs to be re-added again."

However, I am not sure what part they were referring to. I had success sending this form, I was just having an issue with the error message showing on page load, so I am at lost to what they were talking about.

Again, thank you for your help.

View site: https://holthaunt.co.../test_one_offs/

View code:

<!DOCTYPE html>
<head>
	<title>Cartering Form</title>
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
	<script src="https://www.google.com/recaptcha/api.js" async="defer"></script>
	<style type="text/css">
		body
		{
			margin: 0;
		}    
		main
		{	
			display: flex;
			flex-direction: column;
			justify-content: space-between;
			width: 98%;
			margin: auto;
		}
		form
		{	display: flex;
			flex-direction: column;
			width: 100%;
			margin: auto;		
		}
		.line
		{
			display: flex;
			flex-direction: row;
			flex-wrap: nowrap;
			justify-content: space-around;
			width: 100%;
		}
		.line04, .line05
		{
			justify-content: flex-start;
			padding-left: 1em;
		}
		input
		{	width: 100%;
			height: 2em;
		}
		.line04 input
		{	
			display: flex;
			justify-content: flex-start;
			align-items: flex-start;
			width: 80%;
			height: 6em;
		}
		p
		{
			width: 45%;
		}
		.line04 p
		{
			width: 100%;
		}
		.line05
		{
			width: 100%;
		}
		.line05 input
		{
			background: #077A3D;
			color: white;
			height: 2em;
			margin: auto;
		}
		.phpMsg
		{
			width: 80%;
			height: 2em;
			padding-bottom: .1325em;
			padding-top: .1325em;
		}
		span
		{
			color: red;
		}
		.g-recaptcha
		{
			
		}
	</style>
</head>
<body>
 <!-- EMAIL VALIDATION -->
	<main>	
		<form action="<?= $_SERVER['PHP_SELF'] ?>" method="post">
			<div class="line line01">
				<p>
					<label>Name
						<input type="text" name="name" required placeholder="Your Name" required >
					</label> 
				</p>
				<p>
					<label>Email 
						<input type="email" name="email_address" placeholder="[email protected]" required>
					</label>
				</p>
			</div>
			<div class="line line02">
				<p>
					<label>Date of Event
						<input type="date" name="date">
					</label> 
				</p>
				<p>
					<label>Phone
						<input class="phone" type="tel" name="phone_num" placeholder="(555) 123-0000" required>
					</label>
				</p>
			</div>
			<div class="line line03">
				<p>
					<label>Number of People
						<input type="number" name="num_people">
					</label> 
				</p>
				<p>
					<label>Type of Event
						<input type="text" name="type_event">
					</label>
				</p>
			</div>
			<div class="line line04">
				<p>
					<label>Message
						<input type="text" name="message">
					</label>
				</p>
			</div>
			<div class="line line05">
				<p>
					<input type="Submit" value="Submit"/>
				</p>
			</div>
		</form>
		<div class="phpMsg">
			<?php
				if ($_SERVER['REQUEST_METHOD'] == 'POST') {
			      $secret = ''; //intentionally omitted
			      $url = "https://www.google.com/recaptcha/api/siteverify?secret=$secret&response=".$_POST['g-recaptcha-response'];
			      $verify = json_decode(file_get_contents($url));

			      if ($verify->success) {
			        $to = "[email protected]"; //intentionally omitted
			        $subject = "Cartering For My Event";
			        $message = "Name:  " . $_POST['name']. "\r\n";
			        $message .= "Email: " . $_POST['email_address']. "\r\n";
			        $message .= "Phone Number:  " . $_POST['phone_num']. "\r\n";
			        $message .= "Date of Event: " . $_POST['date']. "\r\n";
			        $message .= "Expected Number of People: " . $_POST['num_people']. "\r\n";
			        $message .= "Type of Event: " . $_POST['type_event']. "\r\n";
			        $message .= "Message: " . $_POST['message']. "\r\n";
			        if (@mail($to, $subject, $message)) {

			          echo "Your information has been submitted. Henry will contact you shortly to verify and help you plan your event.";
			        } 
			        else {
			          
			          echo "There has been an error. Please ensure you have completed all fields before submitting the form.";
			        }
			      } 
			      else {
			       
			       echo "<span>Error: Please make sure to click reCapthca to verify you are not a robot.</span>";
			      }
		  		}
		    ?>
		</div>
    	<div class="g-recaptcha" data-sitekey="6LdUn7wUAAAAAF4cQ1i2A1Lj8qOr55EWmHqJeEfW"></div> <!--intentionally omitted -->
	</main>
	<script type="text/javascript">
			$(document).ready(function()
			{
			/*** PHONE NUMBER FORMAT ***/
				$(".phone").keypress(function (e)
				{
					if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57))
					{
						return false;
					}
					var curchr = this.value.length;
					var curval = $(this).val();
					if (curchr == 3 && curval.indexOf("(") <= -1)
					{
						$(this).val("(" + curval + ")" + "-");
					}
					else if (curchr == 4 && curval.indexOf("(") > -1)
					{
						$(this).val(curval + ")-");
					}
					else if (curchr == 5 && curval.indexOf(")") > -1)
					{
							$this.val(curval + "-");
					}
					else if (curchr == 9)
					{
						$(this).val(curval + "-");
						$(this).attr('maxlength', '14');
					}
				});
			});
	</script>
</body>
</html>

Was This Post Helpful? 0
  • +
  • -

#6 ArtificialSoldier   User is offline

  • D.I.C Lover
  • member icon

Reputation: 2494
  • View blog
  • Posts: 7,551
  • Joined: 15-January 14

Re: PHP ReCaptcha Showing Error on Page Load

Posted 16 October 2019 - 09:32 AM

The div for the captcha is not inside your form. Nothing from the captcha gets submitted to PHP.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1