Email Sends When I enter A Certain Part of my Page - php

I am having trouble with a contact form for my website. So there are two parts to this problem.
First I want to know how and why every time I enter the contact link of my page, it automatically sends an email, upon entering the page, and when clicking submit (I only want it to do this one) .
So example:
I go to mywebsite.com then I click on the 'Contact Us' link page. Upon taking me to the contact form, an e-mail is sent automatically. I am then allowed to fill out the form and send another e-mail. I want to know how to prevent that from happening and why it happens.
Second. I have seen lots of answered questions about this but none of the ones I have looked up on this website have worked for me so far.
When I click submit, to submit the form, it sends the email but then stays on the same page without clearing all fields or giving a confirmation message. I had also tried to redirect the page to say something like 'message has been sent successfully' or anything on the lines of that.
I am going to post my code below, but here are some notes on what I have tried before I do.
I tried to include a header to redirect after clicking submit. I am either doing that incorrectly or it just does not work.
I have tried the redirection with a java code, but since doing that it automatically sends an email then redirects to the page I stated without actually going to the contact form page.
My code is the php and html in one. I am going to separate the two after I finish it but I want to get it working first before I organize this section.
While looking at my code please do not judge. I am not a professional at this and I do understand that there are errors. I have tried to keep it with 0 errors but just have been adding code on top of code now to try and get this to work and may have added errors. I am open to suggestions in order to achieve the same effect while breaking down my code if possible. One error I do know I have is my form-inline statement. I am intentionally missing the quote at the end because with the quote, the search bar on my site gets messed up.
I have looked into jquery and ajax as well but I would prefer if someone give me a solution using the same format that I currently have the code in, unless the format is the problem I guess.
I changed my actual domain to mydomain.com for the example.
I do understand too that there may be a lot of irrelevant code but I am not sure if any line may be the problem so I tried to make clear what each section of code does for my page and included everything jsut in case one of those may be the problem.
<?php
$nameErr = $emailErr = $numberErr = $websiteErr = "";
$name = $email = $number = $comment = $subject = "";
$datetime = date('d/m/Y H:i:s');
$ipaddress = $_SERVER['REMOTE_ADDR'];
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
}
if (! preg_match("/^[a-zA-Z ]*$/", $name)) {
$nameErr = "Only letters and white space allowed";
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
}
if (! filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
if (empty($_POST["subject"])) {
$subject = "";
} else {
$subject = test_input($_POST["subject"]);
}
if (empty($_POST["number"])) {
$number = "";
} else {
$number = test_input($_POST["number"]);
}
if (empty($_POST["comment"])) {
$comment = "";
} else {
$comment = test_input($_POST["comment"]);
}
}
$email_message = "Form details below.\n\n";
function clean_string($string) {
$bad = array(
"content-type",
"bcc:",
"to:",
"cc:",
"href"
);
return str_replace($bad, "", $string);
}
$email_message .= "Full Name: " . clean_string($name) . "\n";
$email_message .= "E-mail: " . clean_string($email) . "\n";
$email_message .= "Subject: " . clean_string($subject) . "\n";
$email_message .= "ipaddress: " . clean_string($ipaddress) . "\n";
$email_message .= "date and time: " . clean_string($datetime) . "\n";
$email_message .= "Phone#: " . clean_string($number) . "\n";
$email_message .= "Message: " . clean_string($comment) . "\n";
$email_from = $name . '<' . $email_from . '>';
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'From:' . $email_from . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
/* Send the message using mail() function */
$myemail = "contact#mydomain.com";
mail($myemail, $subject, $email_message, $headers);
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
sec_session_start();
?>
<!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">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>My Domain - Contact</title>
<meta name="keywords" content="" />
<meta name="description" content="" />
<link href="../css/style.css" rel="stylesheet" type="text/css" media="screen" />
</head>
<body>
<div id="logo">
<h1><img src="../tab/mydoaminlogo.jpg" alt="" width="780" height="104" /></h1>
</div>
<hr />
<!-- end #logo -->
<div id="header">
<div id="menu">
<ul>
<li>Home</li>
<li class="current_page_item">News</li>
<li>Locations</li>
<li>About</li>
<li>Contact</li>
<?php if (login_check($mysqli) == true) : ?>
<li>Store</li>
<?php else: ?>
<li>LogIn</li>
<?php endif; ?>
<?php if (login_check($mysqli) == true) : ?>
<li>Log Out</li>
<?php else: ?>
<li>Sign-up</li>
</ul>
<?php endif; ?>
</div>
<!-- end #menu -->
<div id="search">
<form method="get" action="" class="form-inline>
<fieldset>
<input type="text" name="s" id="search-text" size="15" />
<input type="submit" id="search-submit" value="Search" />
</fieldset>
</form>
</div>
<!-- end #search -->
</div>
<!-- end #header -->
<!-- end #header-wrapper -->
<div id="page">
<div id="content_wide">
<div class="post">
<div class="entrycontact">
<div class="container">
<form id="contact" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post">
<h3>Contact Us</h3>
<h4>Please fill out completely</h4>
<fieldset>
<input placeholder="Your name" type="text" name="name" value="<?php echo $name;?>" tabindex="1" required autofocus>
<span class="error"> <?php echo $nameErr;?></span>
</fieldset>
<fieldset>
<input placeholder="Your Email Address" type="email" name="email" value="<?php echo $email;?>"tabindex="2" required>
<span class="error"> <?php echo $emailErr;?></span>
</fieldset>
<fieldset>
<input placeholder="Subject" type="tel" name="subject" value="<?php echo $subject;?>"tabindex="2" required>
<span class="error"><?php echo $numberErr;?></span>
</fieldset>
<fieldset>
<input placeholder="Number" type="tel" name="number" value="<?php echo $number;?>"tabindex="3" required>
<span class="error"><?php echo $numberErr;?></span>
</fieldset>
<fieldset>
<textarea placeholder="Type your message here...." name ="comment" tabindex="5" required><?php echo $comment;?></textarea>
</fieldset>
<fieldset>
<button name="submit" type="submit" id="contact-submit" data-submit="...Sending">Submit</button>
</fieldset>
</form>
</div>
</div>
</div>
</div>
<!-- end #content -->
<!-- end #sidebar -->
<div style="clear: both;"></div>
</div>
<!-- end #page -->
<div id="footer"></div>
<!-- end #footer -->
</body>
</html>

Related

Contact Form for my website not working in php [duplicate]

This question already has answers here:
PHP mail function doesn't complete sending of e-mail
(31 answers)
Closed 3 years ago.
I am trying to make a contact form for my website in php, but it seems something wrong somewhere, which i am unable to locate. Can you please help me to locate the error in the following code will be of great help and suggest further improvement on this.
Will of great help.
Thanks in advance.
<?php
// Message Vars
$msg = '';
$msgClass = '';
//check for submit
if (filter_has_var(INPUT_POST, 'submit')) {
//GET FORM DATA
$name = htmlspecialchars($_POST['name']);
$email = htmlspecialchars($_POST['email']);
$message = htmlspecialchars($_POST['message']);
// check required fields
if (!empty($email) && !empty($name) && !empty($message)) {
// passed
// check email
if (filter_var($email, FILTER_VALIDATE_EMAIL) == false) {
//failed
$msg = 'Please use a valid email';
$msgClass = 'alert-danger';
} else{
//passed
// reciepient email
$toEmail = 'myemail#gmail.com';
$subject = 'Contact Request From '.$name;
$body = '<h2> Contact Request</h2>
<h4> Name </h4><p>'.$name.'</p>
<h4> Email </h4><p>'.$email.'</p>
<h4> Message </h4><p>'.$message.'</p>';
// email headers
$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";
if (mail($toEmail, $subject, $body, $headers)) {
// email sent
$msg = ' Your email has been sent';
$msgClass = 'alert-success';
}
}
# code...
} else {
//failed
$msg = ' Please fill in all fields';
$msgClass = 'alert-danger';
// failed
# code...
}
# code...
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Contact Us</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="container" >
<?php if ($msg != ''): ?>
<div class="alert <?php echo $msgClass; ?> "><?php echo $msg; ?></div>
<?php endif; ?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<div class="contact-form" >
<h1>Contact Us</h1>
<div class="txtb" >
<label>Name</label>
<input type="text"
name="name"
class="form-control"
value="<?php echo isset($_POST['name']) ? $name : ''; ?>">
</div>
<div class="txtb" >
<label>Email</label>
<input type="text"
name="email"
class="form-control"
value="<?php echo isset($_POST['email']) ? $email : ''; ?>" >
</div>
<div class="txtb" >
<label>Message</label>
<textarea name="message" class="form-control" ><?php echo isset($_POST['message']) ? $message : ''; ?></textarea>
</div>
<br>
<a type="submit" name="submit" class="btn" >Submit</a>
</form>
</div>
</body>
</html>
I don't know what type of the error you're seeing but there's a little thing to change
You need to change
<a type="submit" name="submit" class="btn" >Submit</a>
to
<input type="submit">

Google Recaptcha v2 With email form, gives http 500 Error

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.

Contact form doesn't work with the new jQuery version (3.3.1)

I was mistaken that I was missing anything from my PHP file. The only thing which makes the contact form working is if I use a way older version of the jQuery but that cannot be the case because I need SSL on my site and Google determines the site unsafe which wants to load unsafe scripts if they are older.
Here is the old version of the scripts:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
window.jQuery || document.write('</script>')
<script type="text/javascript" src="js/jquery-migrate-1.2.1.min.js"></script>
And here is what I was trying to use. I downloaded js files and uploaded to the server but I thinks because of the many function changes my PHP file cannot do the work anymore.
Can somebody help me to update my PHP file because I don't really do coding :o. Tried to understand how it works however I got confused.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="js/jquery-3.3.1.min.js"><\/script>')</script>
<script type="text/javascript" src="js/jquery-migrate-3.0.0.min.js"></script>
I use a template from Styleshout called Kreative101 and modified it in many ways but I didn't touch the contact form nor the PHP file (only inserting the error reporting and the email address).
I don't know if it needs any jQuery script in order to work because I did change that and the Modal Popup stopped working. Now it is back to the original (at least the footer with the scripts). The modal works the contact form doesn't.
Any help will be highly appreciated;).
If a reload the page says the action I took will be repeated
The contact form worked before, I tested it.
Here is the HTML code
<section id="contact">
<div class="row section-head">
<div class="col full">
<h2>Contact</h2>
<p class="desc">Get in touch with us</p>
</div>
</div>
<div class="row">
<div class="col g-7">
<!-- form -->
<form name="contactForm" id="contactForm" method="post" action="">
<fieldset>
<div>
<label for="contactName">Name <span class="required">*</span></label>
<input name="contactName" type="text" id="contactName" size="35" value="" />
</div>
<div>
<label for="contactEmail">Email <span class="required">*</span></label>
<input name="contactEmail" type="text" id="contactEmail" size="35" value="" />
</div>
<div>
<label for="contactSubject">Subject</label>
<input name="contactSubject" type="text" id="contactSubject" size="35" value="" />
</div>
<div>
<label for="contactMessage">Message <span class="required">*</span></label>
<textarea name="contactMessage" id="contactMessage" rows="15" cols="50" ></textarea>
</div>
<div>
<button class="submit">Submit</button>
<span id="image-loader">
<img src="images/loader.gif" alt="" />
</span>
</div>
</fieldset>
</form> <!-- Form End -->
<!-- contact-warning -->
<div id="message-warning"></div>
<!-- contact-success -->
<div id="message-success">
<i class="icon-ok"></i>Your message was sent, thank you!<br />
</div>
</div>
And the PHP code (I inserted the error reporting but I don't know if it's correct.)
<?php
error_reporting(-1);
ini_set('display_errors', 'On');
set_error_handler("var_dump");
// Replace this with your own email address
$siteOwnersEmail = 'info#virtualpropertyreview.com';
if($_POST) {
$name = trim(stripslashes($_POST['contactName']));
$email = trim(stripslashes($_POST['contactEmail']));
$subject = trim(stripslashes($_POST['contactSubject']));
$contact_message = trim(stripslashes($_POST['contactMessage']));
// Check Name
if (strlen($name) < 2) {
$error['name'] = "Please enter your name.";
}
// Check Email
if (!preg_match('/^[a-z0-9&\'\.\-_\+]+#[a-z0-9\-]+\.([a-z0-9\-]+\.)*+[a-z]{2}/is', $email)) {
$error['email'] = "Please enter a valid email address.";
}
// Check Message
if (strlen($contact_message) < 15) {
$error['message'] = "Please enter your message. It should have at least 15 characters.";
}
// Subject
if ($subject == '') { $subject = "Contact Form Submission"; }
// Set Message
$message .= "Email from: " . $name . "<br />";
$message .= "Email address: " . $email . "<br />";
$message .= "Message: <br />";
$message .= $contact_message;
$message .= "<br /> ----- <br /> This email was sent from your site's contact form. <br />";
// Set From: header
$from = $name . " <" . $email . ">";
// Email Headers
$headers = "From: " . $from . "\r\n";
$headers .= "Reply-To: ". $email . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
if (!$error) {
ini_set("sendmail_from", $siteOwnersEmail); // for windows server
$mail = mail($siteOwnersEmail, $subject, $message, $headers);
if ($mail) { echo "OK"; }
else { echo "Something went wrong. Please try again."; }
} # end if - no validation error
else {
$response = (isset($error['name'])) ? $error['name'] . "<br /> \n" : null;
$response .= (isset($error['email'])) ? $error['email'] . "<br /> \n" : null;
$response .= (isset($error['message'])) ? $error['message'] . "<br />" : null;
echo $response;
} # end if - there was a validation error
}
?>
In the comment I suggested to redirect after sending the mail - not sure if you understood what I meant but like this.
$mail = mail( $siteOwnersEmail, $subject, $message, $headers );
header('Location: ?mailsent=' . $mail ? 'true' : 'error' );
That should prevent the form being submitted if the page is reloaded accidentally etc
You could use that GET variable to display a message to report on status of the mail send.
if( !empty( $_GET['mailsent'] ) ){
echo $_GET['mailsent']=='true' ? "your message was sent" : "Sorry, there was an error"; /* etc */
}

spam protection needed on php form - not sure how to implement

I have a pretty basic PHP site and I want a simple spam protection to stop the spam submissions.
I've found one that I like which is a basic 4 character input. Easy to read, small space requirements.
But it says to use a validate.php for the submission action.
My current form's action is to call a the mailer.php (<form id="contact-form" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" class="validate-form">) which is actually included on page load (<?php include 'includes/mailer.php'; ?>).
Can I have two 'actions'? If not, how can I implement the use of this captcha?
When I try adding session_start();
if(isset($_POST["captcha"])&&$_POST["captcha"]!=""&&$_SESSION["code"]==$_POST["captcha"])
{
echo "Correct Code Entered";
//Do you stuff
Just after the opening <?php in mailer.php and then }
else
{
die("Wrong Code Entered");
} just before the closing ?>, the whole website just displays "Wrong code entered" on load.
EDIT:
I'm having trouble understanding where I need to place the various parts of the code and how to tweak it so it works with the existing mailer script.
My unmodified index.php basically consists of the following:
<?php
include 'includes/mailer.php';
?>
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="css/bootstrap.css">
<link rel="stylesheet" href="css/bootstrap-responsive.css">
<link rel="stylesheet" href="css/styles.css">
</head>
<body>
<section id="section-home">
<header>
<!-- header content -->
<!-- navigation -->
</header>
</section>
<section class="banner full-width-container">
<div class="container">
<!-- other body content -->
<div id="contact">
<div id="contact-form-message"><?php print $output; ?></div>
<form id="contact-form" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" class="validate-form">
<p><span style="color:#f7403a;">Fill in the form below to have an expert contact you</span></p>
<div class="form-left">
<div class="control-group">
<label for="name" class="assistive control-label">Name:</label>
<div class="controls">
<input type="text" name="name" id="name" value="Your Name" class="replace-default required type-text" />
</div>
</div>
<div class="control-group">
<label for="email" class="assistive control-label">Email: </label>
<div class="controls">
<input type="text" name="email" id="email" value="Your email address" class="replace-default required type-text" />
</div>
</div>
</div><!-- end form-left -->
<div class="form-right">
<div class="control-group">
<label for="subject" class="assistive control-label">Subject: </label>
<div class="controls">
<input type="text" name="subject" id="subject" value="Subject" class="replace-default required type-text" />
</div>
</div>
<div class="control-group">
<label for="telephone" class="assistive control-label">Telephone number </label>
<div class="controls">
<input type="text" name="telephone" id="telephone" value="Your phone number" class="replace-default required type-text" />
</div>
</div>
</div><!-- end form-right -->
<div class="control-group">
<label for="message" class="assistive control-label">Message: </label>
<div class="controls">
<textarea name="message" id="message" class="replace-default required type-textarea full-width" rows="5" cols="20">The type of enquiry (e.g. Motor Accident) and a brief message</textarea>
</div>
</div>
<div class="control-group">
<div class="controls">
<input type="submit" id="submit" name="submit" class="btn btn-stacks" value="Send Message"/>
<div id="sending-message"><img src="img/ajax-loader.gif" alt="" /></div>
</div>
</div>
</form>
</div>
</div>
</section>
<footer class="full-width-container" id="footer-section">
<div class="container">
<!-- footer content -->
</div>
</footer>
<!-- ============================================== -->
<script src="js/modernizr-1.7.min.js"></script>
<script src="js/jquery-1.8.2.min.js"></script>
<script src="js/bootstrap.js"></script>
<script src="js/jquery.validate.min.js"></script>
<script src="js/jquery.flexslider-min.js"></script>
<script src="js/waypoints.min.js"></script>
<script src="js/jquery.scrollTo-1.4.3.1-min.js"></script>
<script src="js/custom.js"></script>
</body>
</html>
And my unmodified mailer.php consist of:
<?php
function cleanInput($input){
$input = trim($input);
if(strlen($input)>0){
$input = htmlspecialchars(stripslashes($input));
}
return $input;
}
$name = '';
$email = '';
$subject = '';
$message = '';
$telephone = '';
$output = '';
if ( isset($_POST['submit']) || isset($_GET['ajax']) == 'true'){
//set up for form fields
$name = cleanInput($_POST['name']);
$email = cleanInput($_POST['email']);
$subject = cleanInput($_POST['subject']);
$telephone = cleanInput($_POST['telephone']);
$message = cleanInput($_POST['message']);
$output ='';
$regex = "/^([a-z0-9\\+_\\-]+)(\\.[a-z0-9\\+_\\-]+)*#([a-z0-9\\-]+\\.)+[a-z]{2,6}$/ix";
//do some basic validation
if( $name == '' || $name == 'Full Name' ){ $output = '<li class="alert alert-error">Please enter your name.</li>'; }
if ( !preg_match( $regex, $email ) || $email == 'Email address' ) {
$output .= '<li class="alert alert-error">Please check that your email address is valid</li>';
}
if( $subject == '' || $subject == 'Subject' ){ $output .= '<li class="alert alert-error">Please enter a subject</li>'; }
if( $telephone == '' || $telephone == 'Contact number' ){ $output .= '<li class="alert alert-error">Please enter a contact number</li>'; }
if( $message == '' || $message == 'Your Query' ){ $output .= '<li class="alert alert-error">Please enter a message</li>'; }
//if there are errors, add them to the list here
if ( $output!='' ){
$output = '<div class=""><ul class="unstyled">' . $output . '</ul></div>';
}
//if no errors, try to send the form
else {
/*Put the email address to send to here*/
$to = "email1#domain.com.au";
$headers = 'From: noreply#domain.com.au' . "\r\n";
$headers .= 'Cc: '. $email . "\r\n";
$headers .= 'Bcc: email2#domain.com.au' . ', ' . 'email3#domain.com.au' . ', ' . 'email4#otherdomain.com.au' . "\r\n";
$subject = $subject;
$body = "Name: $name\n\n"
. "Email: $email\n\n"
. "Subject: $subject\n\n"
. "Message: $message"
;
$messageOK = ( mail($to, 'Web Enquiry from the landing page for: ' . $subject, $body, $headers ));
//check if the mail was sent or not
if ( $messageOK ){
$output = '<div class="alert alert-success"><p>Thank you for getting in touch. We will be in contact soon.</p></div>';
}
else {
$output = '<div class="alert alert-error"><p>We could not send your message. Please try again.</p></div>';
}
}
//if ajax is being used, output the message
if ( isset($_GET['ajax']) == 'true' ){
print $output;
}
}
?>
Any information that helps me understand what is required to use this captcha code would be greatly appreciated
You could use a random number generated when form is generated, then passing the value using POST AND $_SESSION, and then compare 2 to see if they match. This is for bot protection/spam.
Would you like an example?
EDIT, didn't fully read the question.
What you want to do is to decide whether the page is loaded as POST request, if is not, then display the form, if is, validate $_POST fields and/or send email.
session_start();
$error = null;
if(isset($_POST["captcha"])&&$_POST["captcha"]!=""&&$_SESSION["code"]==$_POST["captcha"])
{
echo "Correct Code Entered";
//Do you stuff`
else
{
$error = "invalid captcha image, please try again!";
}
//the rest of your HTML
//after the recaptcha image HTML
echo isset($error)? $error: '';
This will stop the page from dieing because of the failed captcha, and will produe an error message of 'Invalid captcha image' if the capthc was false.

PHP contact form with HTML5 validation, display a message?

I have a working php contact form, with HTML5 validation for inputs ( added required to them, and type name/email), but I have one problem.
when message is sent it opens a new tab and it says thank you your message was sent, which is normal because of process.php
<?php
//Retrieve form data.
//GET - user submitted data using AJAX
//POST - in case user does not support javascript, we'll use POST instead
$name = ($_GET['name']) ? $_GET['name'] : $_POST['name'];
$email = ($_GET['email']) ?$_GET['email'] : $_POST['email'];
$website = ($_GET['website']) ?$_GET['website'] : $_POST['website'];
$comment = ($_GET['comment']) ?$_GET['comment'] : $_POST['comment'];
//flag to indicate which method it uses. If POST set it to 1
if ($_POST) $post=1;
//Simple server side validation for POST data, of course,
//you should validate the email
if (!$name) $errors[count($errors)] = 'Please enter your name.';
if (!$email) $errors[count($errors)] = 'Please enter your email.';
if (!$comment) $errors[count($errors)] = 'Please enter your message.';
//if the errors array is empty, send the mail
if (!$errors) {
//recipient - change this to your name and email
$to = 'youremail#email.com';
//sender
$from = $email;
//subject and the html message
$subject = 'Hello from ' . $name;
$message = '
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head></head>
<body>
<table>
<tr><td>Name: </td><td>' . $name . '</td></tr>
<tr><td>Email: </td><td>' . $email . '</td></tr>
<tr><td>Message: </td><td>' . nl2br($comment) . '</td></tr>
</table>
</body>
</html>';
//send the mail
$result = sendmail($to, $subject, $message, $from);
//if POST was used, display the message straight away
if ($_POST) {
if ($result) echo 'Thank you! We have received your message.';
else echo 'Sorry, unexpected error. Please try again later';
//else if GET was used, return the boolean value so that
//ajax script can react accordingly
//1 means success, 0 means failed
} else {
echo $result;
}
//if the errors array has values
} else {
//display the errors message
for ($i=0; $i<count($errors); $i++) echo $errors[$i] . '<br/>';
echo 'Back';
exit;
}
//Simple mail function with HTML header
function sendmail($to, $subject, $message, $from) {
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";
$headers .= 'From: ' . $from . "\r\n";
$result = mail($to,$subject,$message,$headers);
if ($result) return 1;
else return 0;
}
?>
but how can I make it show the message under submit button?
this is HTML side
<form method="post" action="process.php">
<div class="element">
<label><i class="icon-user"></i></label>
<input type="name" name="name" placeholder="write your name here" class="text" required/>
</div>
<br>
<div class="element">
<label><i class="icon-envelope"></i></label>
<input type="email" name="email" placeholder="write your e-mail here" class="text" required/>
</div>
<br>
<div class="element">
<label><i class="icon-comment"></i></label>
<textarea name="comment" placeholder="write your message here" class="text textarea"required></textarea>
</div>
<br>
<div class="element el-submit">
<input class="submit" type="submit" id="submit"/>
</div>
</form>
I mean, when I press submit button and it's alright I want to display a message like "your message was sent", but I want it under submit button, not in a new page
Make the file into one so that you POST data to the same file as below
<?php
if($_POST) //If the form is submitted
{
$notification=""; //Used for catching all your messages
//Retrieve form data.
//GET - user submitted data using AJAX
//POST - in case user does not support javascript, we'll use POST instead
$name = ($_GET['name']) ? $_GET['name'] : $_POST['name'];
$email = ($_GET['email']) ?$_GET['email'] : $_POST['email'];
$website = ($_GET['website']) ?$_GET['website'] : $_POST['website'];
$comment = ($_GET['comment']) ?$_GET['comment'] : $_POST['comment'];
//flag to indicate which method it uses. If POST set it to 1
if ($_POST) $post=1;
//Simple server side validation for POST data, of course,
//you should validate the email
if (!$name) $errors[count($errors)] = 'Please enter your name.';
if (!$email) $errors[count($errors)] = 'Please enter your email.';
if (!$comment) $errors[count($errors)] = 'Please enter your message.';
//if the errors array is empty, send the mail
if (!$errors) {
//recipient - change this to your name and email
$to = 'youremail#email.com';
//sender
$from = $email;
//subject and the html message
$subject = 'Hello from ' . $name;
$message = '
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head></head>
<body>
<table>
<tr><td>Name: </td><td>' . $name . '</td></tr>
<tr><td>Email: </td><td>' . $email . '</td></tr>
<tr><td>Message: </td><td>' . nl2br($comment) . '</td></tr>
</table>
</body>
</html>';
//send the mail
$result = sendmail($to, $subject, $message, $from);
//if POST was used, display the message straight away
if ($_POST) {
if ($result) echo 'Thank you! We have received your message.';
else $notification.= 'Sorry, unexpected error. Please try again later';
//else if GET was used, return the boolean value so that
//ajax script can react accordingly
//1 means success, 0 means failed
} else {
$notification.= $result;
}
//if the errors array has values
} else {
//display the errors message
for ($i=0; $i<count($errors); $i++) echo $errors[$i] . '<br/>';
$notification.= 'Back';
exit;
}
//Simple mail function with HTML header
function sendmail($to, $subject, $message, $from) {
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";
$headers .= 'From: ' . $from . "\r\n";
$result = mail($to,$subject,$message,$headers);
if ($result) return 1;
else return 0;
}
} //First If loop
?>
<form method="post" action="process.php">
<div class="element">
<label><i class="icon-user"></i></label>
<input type="name" name="name" placeholder="write your name here" class="text" required/>
</div>
<br>
<div class="element">
<label><i class="icon-envelope"></i></label>
<input type="email" name="email" placeholder="write your e-mail here" class="text" required/>
</div>
<br>
<div class="element">
<label><i class="icon-comment"></i></label>
<textarea name="comment" placeholder="write your message here" class="text textarea"required></textarea>
</div>
<br>
<div class="element el-submit">
<input class="submit" type="submit" id="submit"/>
<?php
if(!empty($notification)) //This will display notification after submit
{
echo $notification;
}
?>
</div>
</form>
You can also make use of AJAX to achieve what you required.
The following tutorials are the best samples.
http://net.tutsplus.com/tutorials/javascript-ajax/submit-a-form-without-page-refresh-using-jquery/
http://www.9lessons.info/2009/04/submit-form-jquery-and-ajax.html
http://www.phpeveryday.com/articles/jQuery-AJAX-Form-Submission-P973.html
If you don't want to show that on next page create pop up for show the Thank you message its look great.
use your html code in this way.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<script>
function myFunction()
{
alert("Thanks for mail!");
}
</script>
</head>
<body>
<form method="post" action="process.php">
<div class="element">
<label><i class="icon-user"></i></label>
<input type="name" name="name" placeholder="write your name here" class="text" required/>
</div>
<br>
<div class="element">
<label><i class="icon-envelope"></i></label>
<input type="email" name="email" placeholder="write your e-mail here" class="text" required/>
</div>
<br>
<div class="element">
<label><i class="icon-comment"></i></label>
<textarea name="comment" placeholder="write your message here" class="text textarea"required></textarea>
</div>
<br>
<div class="element el-submit">
<input type="button" onclick="myFunction()" value="Submit">
</div>
</form>
</body>
</html>
important point missed in replies so far is the action="some.php" that should be changed to action="" should you delete the server-side PHP; hence, action of "post" is inside the contact form. I found a comprehensive tutorial on this subject relating HTML5 CSS3 and PHP here.

Categories