Google Recaptcha v2 With email form, gives http 500 Error - php

Using an html form for a "contact us". This passes name, email, & message to a .php script and it works well. Add the Google recaptua v2 to this form gives a http 500 Error. This post and the code have been edited to reflect the KaplanKomputing tutorial suggested by Chris White.
You can visit the working form without recaptcha, and nonworking recaptcha here:
https://coinsandhistory.com#contact
The "Google site key" I'll call here "XXXX-Google-site" and "YYYY-Google-secret".
1st the contact form html, you don't need the css styling nor the stripslashes from the tutorial.
<!DOCTYPE html>
<html>
<head>
<script src="https://www.google.com/recaptcha/api.js" async defer>
</script>
<link rel="stylesheet" href="../css/send-mail.css">
</head>
<body>
<!-- https://stackoverflow.com/questions/27188436/html-php-contact-form-
email/55962553 -->
<!-- https://kaplankomputing.com/blog/tutorials/
recaptcha-php-demo-tutorial/ -->
<form action="send-mail_SO2_recapt.php" method="post"
enctype="multipart/form-data" name="myemailform">
<div>
<span>Name </span>
<input type="text" name="name" value="" placeholder="Your Name">
</div>
<div>
<span>Email </span>
<input type="email" name="web_email" autocapitalize="off"
autocorrect="off"
value="" placeholder="youremail#domain.com">
</div>
<div>
<span>messgae </span>
<textarea name="message" placeholder="message"></textarea>
</div>
<!-- Google v2 Recaptua Form -->
<div class="g-recaptcha" data-sitekey="XXXX-Google-site"></div>
<br/>
<div class="code">
<button><input type="submit" name="submit" value="Send"></button>
</div>
<i class="clear" style="display: block"></i>
</div>
</form>
</body>
</html>
And then the send-mail.php script. I called mine "send-mail_SO2_recapt.php".
<?php
/* error reporting, should rmv from working form */
error_reporting(E_ALL);
ini_set('display_errors', 1);
if(!isset($_POST['submit']))
{
//This page should not be accessed directly. Need to submit the form.
echo "error; you need to submit the form!";
}
$name = $_POST["name"];
$visitor_email = $_POST['web_email'];
$message = $_POST["message"];
$response = $_POST["g-recaptcha-response"];
//Validate first
if(empty($name)||empty($visitor_email))
{
echo "Name and email are needed!";
exit;
}
if(IsInjected($visitor_email))
{
echo "Bad email value!";
exit;
}
$url = "https://google.com/recaptcha/api/siteverify";
$data = array(
"secret" => "YYYY-Google-secret",
"response" => $_POST["g-recaptcha-response"]);
$options = array(
"https" => array (
"method" => "POST",
"content" => https_build_query($data)
)
);
$context = stream_context_create($options);
$verify = file_get_contents($url, false, $context);
$captcha_success=json_decode($verify);
if ($captcha_success=>success==false) {
echo "<p>You are a bot! Go away!</p>"; }
else if ($captcha_success=>success==true) {
echo "<p>You are not not a bot!</p>"; }
// $email_from = 'info#coinsandhistory.com';//<== update the email address
$email_from = "$visitor_email";
$email_subject = "New Form submission";
$email_body = "You have received a new message from $name.\n".
"sender's email:\n $email_from\n".
"Here is the message:\n $message";
$to = "youremail#yourdomain.com"; //<== update the email address
$headers = "From: $email_from \r\n";
$headers .= "Reply-To: $visitor_email \r\n";
//Send the email!
mail($to,$email_subject,$email_body,$headers);
//done. redirect to thank-you page.
header('Location: thank_you_SO2.html');
exit;
// Function to validate against any email injection attempts
?>
If you supply code samples, please indicate what form it is: eg html, php, javascript. I can't believe I'm the 1st person to try to use a simple Google recaptua in a contact form but this question doesn't appear plainly anywhere.

i see number of errors in your code. try the following code and see if it works, it is tested and working for me. it is not based on your followed tutorial and uses curl for verification instead.
Your biggest mistakes i think are that there is no isInfected function defined, => in place of -> and sometime file_get_contents doenst work on all servers.
HTML:
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
<form action="" method="post">
<div>
<span>Name</span>
<input type="text" name="name" placeholder="Your Name" required>
</div>
<div>
<span>Email</span>
<input type="email" name="web_email" placeholder="youremail#domain.com" required>
</div>
<div>
<span>Messgae</span>
<textarea name="message" placeholder="message" required></textarea>
</div>
<!-- Google v2 Recaptcha Form -->
<div class="g-recaptcha" data-sitekey="YOUR_SITE_KEY"></div>
<div class="code">
<input type="submit" name="submit" value="Send">
</div>
</form>
PHP CODE:
<?php
//check form is submitted
if( isset($_POST['submit']) ){
// get values
$error = '';
$name = $_POST["name"];
$visitor_email = $_POST['web_email'];
$message = $_POST["message"];
//Validate first
if(empty($name)||empty($visitor_email)) {
$error = "Name and email are needed!";
}
//handle captcha response
$captcha = $_REQUEST['g-recaptcha-response'];
$handle = curl_init('https://www.google.com/recaptcha/api/siteverify');
curl_setopt($handle, CURLOPT_POST, true);
curl_setopt($handle, CURLOPT_POSTFIELDS, "secret=YOUR_SECRET_KEY&response=$captcha");
curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($handle);
$explodedArr = explode(",",$response);
$doubleExplodedArr = explode(":",$explodedArr[0]);
$captchaConfirmation = end($doubleExplodedArr);
print_r($doubleExplodedArr);
if ( trim($captchaConfirmation) != "true" ) {
$error = "<p>You are a bot! Go away!</p>";
}
if( empty($error) ){ //no error
// mail than
$to = "youremail#mail.com";
$email_subject = "New Form submission";
$email_body = "You have received a new message from ".$name.".\n".
"sender's email:\n ".$visitor_email."\n".
"Here is the message:\n ".$message;
$headers = "From: ".$visitor_email." \r\n";
$headers .= "Reply-To: ".$visitor_email." \r\n";
//Send the email!
$mail_check = mail($to,$email_subject,$email_body,$headers);
if( $mail_check ){
// echo "all is well. mail sent";
header('Location: thank_you.html');
} else {
echo "mail failed. try again";
}
} else {
echo $error;
}
}
?>

Here is an answer which worked for me. I'd like to really thank Galzor as his answers helped me a lot. The base Code I got from Code Geek and I added stuff here to add in the form. This format hopefully eliminated the confusion on exactly what to include in the Google "SITE-KEY" and "SECRET-KEY" as it gets them as variables before processing them in a string. These are actually 40 character strings. The sucessful captcha goes to a landing page.
This is the HTML send-mail_form.html
<!DOCTYPE html>
<html>
<head>
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
</head>
<body>
<!-- form goes in the body of HTML -->
<form action="send-mail_form.php" method="post">
<div>
<span>Name</span>
<input type="text" name="name" value="" placeholder="Your Name" required>
</div>
<div>
<span>Email</span>
<input type="email" name="web_email" placeholder="youremail#domain.com" required>
</div>
<div>
<span>Messgae</span>
<textarea name="message" placeholder="message" required></textarea>
</div>
<!-- Google v2 Recaptcha Form -->
<div class="g-recaptcha" data-sitekey="SITE-KEY"></div>
<div class="code">
<input type="submit" name="submit" value="Send">
</div>
</form>
</body>
</html>
And this will be the called send-mail_form.php. I won't bother with showing the thank_you_SO2.html here.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
$web_email;$message;$captcha;
// check form is submitted
if(isset($_POST['web_email']) ){
// get values
$name= $_POST["name"];
$visitor_email= $_POST['web_email'];
$message= $_POST['message'];
//Validate first
if(empty($name)||empty($visitor_email)) {
$error = "Name and email are needed!";
}
if(isset($_POST['g-recaptcha-response'])){
$captcha=$_POST['g-recaptcha-response'];
}
if(!$captcha){
echo '<h2>Please check the the captcha form.</h2>';
exit;
}
$secretKey = "SECRET-KEY";
$ip = $_SERVER['REMOTE_ADDR'];
// post request to server
$url = 'https://www.google.com/recaptcha/api/siteverify?secret=' .
urlencode($secretKey) . '&response=' . urlencode($captcha);
$response = file_get_contents($url);
$responseKeys = json_decode($response,true);
// should return JSON with success as true
if($responseKeys["success"]) {
// echo '<h3>Thanks for contacting us</h3>';
// mail then
$to = "youremail#yourdomain.com";
$email_subject = "CG Recaptcha Form2 submission";
$email_body = "You have received a new message from ".$name.".\n".
"sender's email:\n ".$visitor_email."\n".
"Here is the message:\n ".$message;
//Send the email!
$mail_check = mail($to,$email_subject,$email_body);
if( $mail_check ){
// echo "all is well. mail sent";
header('Location: thank_you_SO2.html');
}
else {
echo '<h2>You are a spammer ! Go Away</h2>';
}
}
}
?>
There are some unneccesary items, the error checking at the top can probably be removed. Also will the Google site verify will work with https://google.com/recaptcha/api/siteverify?secret=.... ? Actually on testing it seems to fail sometimes without the www so perhaps best to keep it.

Related

PHP Form redirects to blank screen after hitting submit

I feel like this is a stupid question to ask with a really simple answer, I have tried looking at the other questions related to this topic but i dont really get it from those.
I have a simple HTML and PHP contact form, it is redirecting to a blank page.
I get that i will probably need a "header" part in there somewhere, but then how would the status messages from the PHP show up in the browser if it redirects back to the previous page?
I have tried adding in the redirect and that works, but no messages show up saying that it is successful.
So far I haven't even verified that the email function is working, because I am trying to sort this part out.
HTML CODE
<div class="col-lg-8 mt-5 mt-lg-0" data-aos="fade-left">
<h2>Simple PHP Contact Form</h2>
<div class="contactFrm">
<?php if(!empty($statusMsg)){ ?>
<p class="statusMsg <?php echo !empty($msgClass)?$msgClass:''; ?>">
<?php echo $statusMsg; ?>
</p>
<?php } ?>
<form action="forms/contact.php" method="post">
<h4>Name</h4>
<input type="text" name="name" placeholder="Your Name" required="">
<h4>Email </h4>
<input type="email" name="email" placeholder="email#example.com" required="">
<h4>Subject</h4>
<input type="text" name="subject" placeholder="Write subject" required="">
<h4>Message</h4>
<textarea name="message" placeholder="Write your message here" required=""> </textarea>
<input type="submit" name="submit" value="Submit">
<div class="clear"> </div>
</form>
</div>
</div>
PHP CODE
<?php
error_reporting(-1);
ini_set('display_errors', 'On');
set_error_handler("var_dump");
$statusMsg = '';
$msgClass = '';
if(isset($_POST['submit'])){
// Get the submitted form data
$email = $_POST['email'];
$name = $_POST['name'];
$subject = $_POST['subject'];
$message = $_POST['message'];
// Check whether submitted data is not empty
if(!empty($email) && !empty($name) && !empty($subject) && !empty($message)){
if(filter_var($email, FILTER_VALIDATE_EMAIL) === false){
$statusMsg = 'Please enter your valid email.';
$msgClass = 'errordiv';
}else{
// Recipient email
$toEmail = '985thenquiries#protonmail.com';
$emailSubject = 'Contact Request Submitted by '.$name;
$htmlContent = '<h2>Contact Request Submitted</h2>
<h4>Name</h4><p>'.$name.'</p>
<h4>Email</h4><p>'.$email.'</p>
<h4>Subject</h4><p>'.$subject.'</p>
<h4>Message</h4><p>'.$message.'</p>';
print("I worked?");
// Set content-type header for sending HTML email
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
// Additional headers
$headers .= 'From: '.$name.'<'.$email.'>'. "\r\n";
// Send email
if(mail($toEmail,$emailSubject,$htmlContent,$headers)){
$statusMsg = 'Your contact request has been submitted successfully !';
$msgClass = 'succdiv';
print("submission successful");
print($name);
}else{
$statusMsg = 'Your contact request submission failed, please try again.';
$msgClass = 'errordiv';
print("sub brok");
}
}
}else{
$statusMsg = 'Please fill all the fields.';
$msgClass = 'errordiv';
}
}
?>

How to show a success dialog box after submitting the form in html?

I'm a newbie to php and html, I've created a form which will accept the inputs from user and will send it to a specified Email id. Everything is working fine but on submitting the form, it goes to another new page.
How this can be replaced with a dialog box as a confirmation message upon submitting the form?
HTML -
<form method="POST" name="contactform" action="contact-form-handler.php">
<p>
<label for='name'>Your Name:</label> <br>
<input type="text" name="name">
</p>
<p>
<label for='email'>Email Address:</label> <br>
<input type="text" name="email"> <br>
</p>
<p>
<label for='message'>Message:</label> <br>
<textarea name="message"></textarea>
</p>
<input type="submit" value="Submit"><br>
</form>
PHP -
<?php
$errors = '';
$myemail = 'mymail#gmail.com';//<-----Put Your email address here.
if(empty($_POST['name']) ||
empty($_POST['email']) ||
empty($_POST['message']))
{
$errors .= "\n Error: all fields are required";
}
$name = $_POST['name'];
$email_address = $_POST['email'];
$message = $_POST['message'];
if (!preg_match(
"/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i",
$email_address))
{
$errors .= "\n Error: Invalid email address";
}
if( empty($errors))
{
$to = $myemail;
$email_subject = "Contact form submission: $name";
$email_body = "You have received a new message. ".
" Here are the details:\n Name : $name \n Email : $email_address \n Message : $message";
$headers = "From: $myemail\n";
$headers .= "Reply-To: $email_address";
mail($to,$email_subject,$email_body,$headers);
//redirect to the 'thank you' page
echo "Your Message successfully sent, we will get back to you ASAP.";
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Contact form handler</title>
</head>
<body>
<!-- This page is displayed only if there is some error -->
<?php
echo nl2br($errors);
?>
</body>
</html>
You can submit the form in the same page and can simply show JavaScript alert message to the users.
Below code will help you resolving your issue.
<?php
if(isset($_POST['btnSubmit'])){
$errors = '';
$myemail = 'mymail#gmail.com';//<-----Put Your email address here.
if(empty($_POST['name']) ||
empty($_POST['email']) ||
empty($_POST['message']))
{
$errors .= "\n Error: all fields are required";
}
$name = $_POST['name'];
$email_address = $_POST['email'];
$message = $_POST['message'];
if (!preg_match(
"/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i",
$email_address))
{
$errors .= "\n Error: Invalid email address";
}
if( empty($errors))
{
$to = $myemail;
$email_subject = "Contact form submission: $name";
$email_body = "You have received a new message. ".
" Here are the details:\n Name : $name \n Email : $email_address \n
Message : $message";
$headers = "From: $myemail\n";
$headers .= "Reply-To: $email_address";
mail($to,$email_subject,$email_body,$headers);
//redirect to the 'thank you' page
//echo "Your Message successfully sent, we will get back to you ASAP.";
}
print("<script>alert('Your Message successfully sent, we will get back to
you ASAP.');</script>");
}
?>
<form method="POST" name="contactform" action="">
<p>
<label for='name'>Your Name:</label> <br>
<input type="text" name="name">
</p>
<p>
<label for='email'>Email Address:</label> <br>
<input type="text" name="email"> <br>
</p>
<p>
<label for='message'>Message:</label> <br>
<textarea name="message"></textarea>
</p>
<input type="submit" value="Submit" name="btnSubmit"><br>
</form>
Hope it helps!
It can be done with following jQuery function:
$(document).ready(function() {
$("[name='contactForm']").submit(function() {
if(confirm("You are about to submit the form. Are you sure?")){
window.location = "http://www.google.com/"
};
});
});
But you will be redirected to a blank new page anyways. In order to prevent that you can either use an AJAX submit(simply add AJAX construction inside the function) or do the redirect using JavaScript function I added to jQuery script

php reCaptcha will not return confirmation after submission

I have a contact form with the reCaptcha on my website www.boakustikk.no
Almost everything is working. The email is delivered, only if reCaptcha is performed correctly, as it should be. But the return confirmation is only a blank, empty page, in both cases. It seems that the function in line 31 to 41, in the form.php, is not working. Here is my form.php and the form.html :
form.php:
<?php
if(isset($_POST['submit']) && !empty($_POST['submit'])):
if(isset($_POST['g-recaptcha-response']) && !empty($_POST['g-recaptcha-response'])):
//your site secret key
$secret = 'secret';
//get verify response data
$verifyResponse = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$secret.'&response='.$_POST['g-recaptcha-response']);
$responseData = json_decode($verifyResponse);
if($responseData->success):
//contact form submission code
$name = !empty($_POST['name'])?$_POST['name']:'';
$email = !empty($_POST['email'])?$_POST['email']:'';
$message = !empty($_POST['message'])?$_POST['message']:'';
$to = 'kontakt#boakustikk.no';
$subject = 'New contact form have been submitted';
$htmlContent = "
<h1>Henvendelse fra din hjemmeside</h1>
<p><b>Navn: </b>".$name."</p>
<p><b>E-post: </b>".$email."</p>
<p><b>Melding: </b>".$message."</p>
";
// Always set content-type when sending HTML email
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
// More headers
$headers .= 'From:'.$name.' <'.$email.'>' . "\r\n";
//send email
#mail($to,$subject,$htmlContent,$headers);
$succMsg = 'Your contact request have submitted successfully.';
else:
$errMsg = 'Robot verification failed, please try again.';
endif;
else:
$errMsg = 'Please click on the reCAPTCHA box.';
endif;
else:
$errMsg = '';
$succMsg = '';
endif;
?>
form.html:
<form action="form.php" method="POST">
<input type="text" name="name" placeholder="Ditt navn" size="43" /><br><br>
<input type="text" name="email" placeholder="Din E-post" size="43" /><br><br>
<textarea type="text" name="message" rows="8" cols="41"></textarea><br><br>
<div class="g-recaptcha" data-sitekey="sitekey"></div><br>
<input type="submit" name="submit" value="SJEKK reCAPTCHA OG SEND MELDING">
</form>
You add text to $succMsg or $errMsg as appropriate, but you never echo them to the page. Nor do you output any other content as far as I can see. So the end result of executing form.php will be a blank page returned to the browser.
You need to output the messages, the simplest implementation would be:
echo $succMsg;
or
echo $errMsg;
in the error case.
But of course you might want to add some HTML markup and CSS to format it nicely, depending on your requirements.

Unable to replace form with message on submission

I've created an HTML5 form, which incorporates reCAPTCHA, and I've also written a PHP script that sends an email when the form is submitted. At the moment, the script redirects the user to an error or thankyou page, but I'm trying to adjust it to dynamically replace the form within a message within the same page.
I've tried the following script, but it displays the message as soon as the page loads, before any user interaction.
PHP/HTML:
<?php
if ($_POST) {
// Load reCAPTCHA library
include_once ("autoload.php");
$name = Trim(stripslashes($_POST['name']));
$email = Trim(stripslashes($_POST['email']));
$message = Trim(stripslashes($_POST['message']));
$emailFrom = $email;
$emailTo = "my#email.com";
$subject = "Contact Request";
// Prepare email body text
$body = "<strong>Name:</strong> $name <br /> <strong>Email:</strong> $email <br /> <strong>Message:</strong> $message";
$headers .= 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .= "From: $name <$emailFrom>" . "\r\n";
$secret = 'XXX';
$recaptcha = new \ReCaptcha\ReCaptcha($secret);
$resp = $recaptcha->verify($_POST['g-recaptcha-response'],$_SERVER['REMOTE_ADDR']);
echo 'Your message was submitted!';
} else {
?>
<div class="contact-form">
<form role="form" method="post" action="index.php">
<label for="name"><span>Name</span><input type="text" class="input-field" name="name" required data-errormessage-value-missing="Please enter your name." /></label>
<label for="email"><span>Email</span><input type="email" class="input-field" name="email" required data-errormessage-value-missing="Please enter your email address." /></label>
<label for="message"><span>Message</span><textarea name="message" class="textarea-field" required data-errormessage-value-missing="Please enter your message."></textarea></label>
<label><span> </span><div id="recaptcha"><div class="g-recaptcha" data-sitekey="6LcBawsTAAAAAKBPfGs1jApXNRLvR2MIPng0Fxol"></div></div></label>
<label><span> </span><input type="submit" value="" class="submit-button" /></label>
</form>
</div>
<?php
}
?>
I'm new to PHP, so I'm not sure if it's a syntax or semantics issue. Any help would be greatly appreciated!
Here's one way of doing it.
Check to see if the form has been submitted with if(isset($_POST['submit'])). You can also use if($_SERVER['REQUEST_METHOD'] == 'POST') to see if the form has been submitted.
Then we check if the email has been successfully sent, and if it has we set the $success_message variable.
We then check to see if the $success_message variable is set, and if it isn't, we show the form.
Also, note that I added name="submit" to the submit button element. This is how we're checking to see if the form has been submitted.
I also changed stripslashes() to strip_tags() to prevent any malicious code from getting through.
<?php
// Load reCAPTCHA library
include_once ("autoload.php");
if(isset($_POST['submit'])) {
$name = trim(strip_tags($_POST['name']));
$email = trim(strip_tags($_POST['email']));
$message = trim(strip_tags($_POST['message']));
$emailFrom = $email;
$emailTo = "my#email.com";
$subject = "Contact Request";
// Prepare email body text
$body = "<strong>Name:</strong> $name <br /> <strong>Email:</strong> $email <br /> <strong>Message:</strong> $message";
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .= "From: $name <$emailFrom>" . "\r\n";
$secret = 'XXX';
$lang = 'en';
$recaptcha = new \ReCaptcha\ReCaptcha($secret);
$resp = $recaptcha->verify($_POST['g-recaptcha-response'],$_SERVER['REMOTE_ADDR']);
// EDIT: repositioned recaptcha from OP's PasteBin script, as requested and adjusted messaging
// changed $success var to $message and added error message
// Original if statement, which redirected the user
if($resp->isSuccess()){
// send the email
if(mail($emailFrom, $subject, $body, $headers)) {
// set the success message
$success_message = 'The form was sent! Yay!';
} else {
// error message
$error_message = 'Could not send email';
}
} else {
$error_message = 'Prove you are a human!';
}
}
?>
<div>
<!-- quick and dirty way to print messages -->
<?php if(isset($success_message)) { echo $success_message; } ?>
<?php if(isset($error_message)) { echo $error_message; } ?>
</div>
<?php if(!isset($success_message)): ?>
<div class="contact-form">
<form role="form" method="post" action="index.php">
<label for="name"><span>Name</span><input type="text" class="input-field" name="name" required data-errormessage-value-missing="Please enter your name." /></label>
<label for="email"><span>Email</span><input type="email" class="input-field" name="email" required data-errormessage-value-missing="Please enter your email address." /></label>
<label for="message"><span>Message</span><textarea name="message" class="textarea-field" required data-errormessage-value-missing="Please enter your message."></textarea></label>
<div class="g-recaptcha" data-sitekey="6LcBawsTAAAAAKBPfGs1jApXNRLvR2MIPng0Fxol"></div>
<script type="text/javascript"
src="https://www.google.com/recaptcha/api.js?hl=<?php echo $lang; ?>">
</script>
<label><span> </span><input type="submit" name="submit" value="" class="submit-button" /></label>
</form>
</div>
<?php endif; ?>

Contact File wont work

on my website I have an automatic contact formular, it runs on my localhost server, but if I load the File onto my Server it won't work. It seems like the submit doesn't work, it doesn't throw an error message it just reloads the page. I've done a lot of code review, but couldn`t find any issue until now.
The strange thing to me is, that the code works on my localhost but not on the server...
You can test it yourself here:
http://144.76.1.46/RequestStream.php
And heres the code:
<?php
$your_email ='censored#gmail.com';
session_start();
$errors = '';
$name = '';
$visitor_email = '';
$user_message = '';
if(isset($_POST['Submit']))
{
$name = $_POST['name'];
$visitor_email = $_POST['email'];
$user_message = $_POST['message'];
///------------Do Validations-------------
if(empty($name)||empty($visitor_email))
{
$errors .= "\n Name and Email are required fields. ";
}
if(IsInjected($visitor_email))
{
$errors .= "\n Bad email value!";
}
if(empty($_SESSION['6_letters_code'] ) ||
strcmp($_SESSION['6_letters_code'], $_POST['6_letters_code']) != 0)
{
//Note: the captcha code is compared case insensitively.
//if you want case sensitive match, update the check above to
// strcmp()
$errors .= "\n The captcha code does not match!";
}
if(empty($errors))
{
//send the email
$to = $your_email;
$subject="New form submission";
$from = $your_email;
$ip = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '';
$body = "A user $name submitted the contact form:\n".
"Name: $name\n".
"Email: $visitor_email \n".
"Message: \n ".
"$user_message\n".
"IP: $ip\n";
$headers = "From: $from \r\n";
$headers .= "Reply-To: $visitor_email \r\n";
mail($to, $subject, $body, $headers);
header('Location: thank-you.html');
}
}
// Function to validate against any email injection attempts
function IsInjected($str)
{
// censored
}
else
{
return false;
}
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Contact Us</title>
<!-- a helper script for vaidating the form-->
<script language="JavaScript" src="censored" type="text/javascript"></script>
</head>
<body>
<?php
if(!empty($errors)){
echo "<p class='err'>".nl2br($errors)."</p>";
}
?>
<div id='contact_form_errorloc' class='err'></div>
<form method="POST" name="contact_form"
action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>">
<p>
<label for='name'>Streamname: </label><br>
<input type="text" name="name" value='<?php echo htmlentities($name) ?>'>
</p>
<p>
<label for='email'>Your Email: (for possible further queries) </label><br>
<input type="text" name="email" value='<?php echo htmlentities($visitor_email) ?>'>
</p>
<p>
<label for='message'>Streamlink and explanation why he should be listed on Lol Streamgalleries: (preferably with links to reliable sources (such as leagepedia for example)</label> <br>
<textarea name="message" rows=8 cols=30><?php echo htmlentities($user_message) ?></textarea>
</p>
<p>
<img src="html-contact-form-captcha/captcha_code_file.php?rand=<?php echo rand(); ?>" id='captchaimg' ><br>
<label for='message'>Enter the code above here :</label><br>
<input id="6_letters_code" name="6_letters_code" type="text"><br>
<small>Can't read the image? click <a href='javascript: refreshCaptcha();'>here</a> to refresh</small>
</p>
<input type="submit" value="Submit" name='submit'>
</form>
<script language="JavaScript">
// Code for validating the form
// Visit http://www.javascript-coder.com/html-form/javascript-form-validation.phtml
// for details
var frmvalidator = new Validator("contact_form");
//remove the following two lines if you like error message box popups
frmvalidator.EnableOnPageErrorDisplaySingleBox();
frmvalidator.EnableMsgsTogether();
frmvalidator.addValidation("name","req","Please provide your name");
frmvalidator.addValidation("email","req","Please provide your email");
frmvalidator.addValidation("email","email","Please enter a valid email address");
</script>
<script language='JavaScript' type='text/javascript'>
function refreshCaptcha()
{
var img = document.images['captchaimg'];
img.src = img.src.substring(0,img.src.lastIndexOf("?"))+"?rand="+Math.random()*1000;
}
</script>
</body>
</html>
Edit:
the error console helped me a little bit, there was a reference error with the javascript file, fixed it now, but sadly still won't work.
you named your button submit but checking for $_POST['Submit']
try isset($_POST['submit'])
or
$_POST['submit'] == 'Submit'

Categories