PHP Email: No data being displayed although email is sent - php

I'm using g-Recaptcha v3 to pass a hidden token and HTML "Contact" form data to form.php file on the localhost, which verifies the g-Recaptcha data, returns a default prompt to end-user and sends an email, via the localhost to the default email address.
The email received does not display data captured, via the HTML "Contact" form. I have tried changing the syntax, I have tried additional "If/Else" statements as well as adding "POST" commands without any success.
HTML contact form section:
<!-- The Contact Section -->
<div class="w3-container w3-content w3-center w3-blue-gray w3-padding-64" style="max-width:1400px" id="contact">
<div class=" w3-container w3-content w3-center" style="max-width:1000px">
<h2 class="w3-wide">Contact</h2>
<p class="w3-opacity"><i>~ Lets Talk About Your Current Needs ~</i></p>
<form id="comment_form" action="form.php " method="post" target="_blank" >
<input class="w3-input w3-border w3-text-gray w3-center" type="text" placeholder="Enter Your First Name: ex. Mark (with no spaces, punctuations or symbols)" name="fname" maxlength="32" pattern="[A-Za-z]{1,32}" required><br>
<input class="w3-input w3-border w3-text-gray w3-center" type="text" placeholder="Enter Your Last Name: ex. Wilson (with no spaces, punctuations or symbols)" name="lname" maxlength="32" pattern="[A-Za-z]{1,32}" required>
<input class="w3-input w3-section w3-border w3-text-gray w3-center" type="text" placeholder="Enter Your Email: ex. yourname#domainname.com" name="email" pattern="^([a-zA-Z0-9_\-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$" required>
<input class="w3-input w3-section w3-border w3-text-gray w3-center" placeholder="Enter Your Phone Number: ex.(112)112-1112 or 1121121112" name="phone" pattern="^(\s*)?(\+)?([- _():=+]?\d[- _():=+]?){10,14}(\s*)?$" required>
<textarea class="w3-input w3-section w3-border w3-text-gray w3-center" placeholder="Please Place Your Comment Here" name="comment" rows="5" required></textarea>
<i class="fa fa-paper-plane-o"></i>
<input type="submit" name="submit" value="SEND MESSAGE" class="w3-text-black"><br><br>
</form>
<script>
// when form is submit
$('#comment_form').submit(function() {
// we stopped it
event.preventDefault();
var fname = $('#fname').val();
var lname = $('#lname').val();
var email = $('#email').val();
var phone = $('#phone').val();
var comment = $("#comment").val();
// needs for recaptacha ready
grecaptcha.ready(function() {
// do request for recaptcha token
// response is promise with passed token
grecaptcha.execute('----------My Public Key----------', {action: 'create_comment'}).then(function(token) {
// add token to form
$('#comment_form').prepend('<input type="hidden" name="g-recaptcha-response" value="' + token + '">');
$.post("form.php",{fname: fname, lname: lname, email: email, phone: phone, comment: comment, token: token}, function(result) {
console.log(result);
if(result.success) {
alert('Thanks for posting your comment!')
} else {
alert('Spammed Message - This Process Will Be Terminated')
}
});
});;
});
});
</script>
form.php
<?php
$fname;$lname;$email;$phone;$comment;$captcha;
if(isset($_POST['fname'])){
$fname=$_POST['fname'];
}if(isset($_POST['lname'])){
$lname=$_POST['lname'];
}if(isset($_POST['email'])){
$email=$_POST['email'];
}if(isset($_POST['phone'])){
$phone=$_POST['phone'];
}if(isset($_POST['comment'])){
$comment=$_POST['comment'];
}if(isset($_POST['token'])){
$captcha=$_POST['token'];
}
if(!$captcha){
echo '<h2>Please check the the captcha form.</h2>';
exit;
}
$secretKey = "--------------My 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);
header('Content-type: application/json');
if($responseKeys["success"]) {
echo json_encode(array('success' => 'true'));
} else {
echo json_encode(array('success' => 'false'));
}
// COLLECT CONTACT FORM DATA
$email = $_POST['email'];
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$number = $_POST['phone'];
$comment = $_POST['comment'];
// FORMAT EMAIL
$to = "default#emailaddress.com";
$headers = "From: {$to} \r\n";
$headers .= "Reply-To: {$email } \r\n";
$subject = "New form submission ... \r\n";
$body = "First Name: {$fname} \r\n";
$body .= "Last Name: {$lname} \r\n";
$body .= "Email: {$email} \r\n";
$body .= "Phone: {$phone } \r\n";
$body .= "Comment: {$comment}";
// SEND EMAIL to DEFAULT RECIPIENT VIA LOCALHOST
$send = mail($to, $subject, $body, $headers);
?>
HTML contact form:
Google g-recaptcha v3 verification prompt:
Email, via contact form, with missing data:

Related

Mail function sending blank values

I am trying to send an email to user account using php mail() function.The mail is sent successfully but the issue is that it is sending me blank emails with no values in them! The code for the contact page that sends the email is as follows:-
<form class="contact-form" method="POST" action="sendemail.php">
<div class="row-fluid">
<div class="span5">
<label>First Name</label>
<input type="text" class="input-block-level" required="required" placeholder="Your First Name" name="name">
<label>Last Name</label>
<input type="text" class="input-block-level" required="required" placeholder="Your Last Name" name="lname">
<label>Email Address</label>
<input type="text" class="input-block-level" required="required" placeholder="Your email address" name="email">
</div>
<div class="span7">
<label>Message</label>
<textarea name="message" id="message" required="required" class="input-block-level" rows="8" name="message"></textarea>
</div>
</div>
<input type="submit" class="btn btn-primary btn-large pull-right" value="Send Message" />
<p> </p>
</form>
and sendemail.php page code is as follows:
<?php
header('Content-type: application/json');
$status = array(
'type'=>'success',
'message'=>'Email sent!'
);
$name = #trim(stripslashes($_POST['name']));
$email = #trim(stripslashes($_POST['email']));
$subject = "An enquiry sir";
$message = #trim(stripslashes($_POST['message']));
$email_from = $email;
$email_to = 'email#email.com';
echo $body = 'Name: ' . $name . "\n\n" . 'Email: ' . $email . "\n\n" . 'Subject: ' . $subject . "\n\n" . 'Message: ' . $message;
$success = #mail($email_to, $subject, $body, 'From: <'.$email_from.'>');
echo json_encode($status);
die;
?>
Why is the output I get blank in my email id, for example:
Name:
Email:
Subject:
Message:
P.N: I am using here a nova template theme.
The form is being submitted via AJAX using the following JavaScript:
var form = $('.contact-form');
form.submit(function () {
$this = $(this);
$.post($(this).attr('action'), function(data) {
$this.prev().text(data.message).fadeIn().delay(3000).fade‌​Out();
},'json');
return false;
});
the form submission code is not submitting the form data. Here is the code you provided:
var form = $('.contact-form');
form.submit(function () {
$this = $(this);
$.post($(this).attr('action'), function(data) {
$this.prev().text(data.message).fadeIn().delay(3000).fade‌​Out();
},'json');
return false;
});
and this is what it should be:
var form = $('.contact-form');
form.submit(function () {
$this = $(this);
$.post($(this).attr('action'), $(this).serialize(), function(data) {
$this.prev().text(data.message).fadeIn().delay(3000).fade‌​Out();
},'json');
return false;
});
Remove the echo from the line that defines $body
From this...
echo $body = 'Name: ' . $name . "\n\n" . 'Email
To this...
$body = 'Name: ' . $name . "\n\n" . 'Email

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 form issues - mobile number not sending

I have been having ongoing issues with this contact form. I am now trying to get the mobile number part to work.
I have been able to get it to work with someone code from here but it loses the format that I would like to keep. Can anyone find a reason why this form is not sending the mobile number?
site: www.krjwoodcraft.com
send.php
<?php
$name = $_POST['name'];
$subject = $_POST['subject'];
$sender = $_POST['email'];
$message= $_POST['message'];
$mobile = $_POST['mobile'];
$your_site_name = "www.krjwoodcraft.com";
$your_email = "rob.catharsis#gmail.com";
// setting header:
$header = "MIME-Version: 1.0\r\n";
$header .= "Content-type: text/html; charset=utf-8\r\n";
$header .= "From: {$name} <{$sender}>\r\n";
// to subject message header
$result = mail($your_email, "Message from ".$your_site_name, nl2br($message), $header);
echo "Your Message has been sent";
?>
contact.js
$(document).ready(function(){
$("#send").click(function(){
var name = $("#name").val();
var email = $("#email").val();
var message = $("#message").val();
var mobile = $("#mobile").val();
var error = false;
if(email.length == 0 || email.indexOf("#") == "-1" || email.indexOf(".") == "-1"){
var error = true;
$("#error_email").fadeIn(500);
}else{
$("#error_email").fadeOut(500);
}
if(message.length == 0){
var error = true;
$("#error_message").fadeIn(500);
}else{
$("#error_message").fadeOut(500);
}
if(name.length == 0){
var error = true;
$("#error_name").fadeIn(500);
}else{
$("#error_name").fadeOut(500);
}
if(error == false){
$("#send").attr({"disabled" : "true", "value" : "Loading..." });
$.ajax({
type: "POST",
url : "send.php",
data: "name=" + name + "&email=" + email + "&subject=" + "You Got Email" + "&message=" + message + "&mobile=" + mobile,
success: function(data){
if(data == 'success'){
$("#btnsubmit").remove();
$("#mail_success").fadeIn(500);
}else{
$("#mail_failed").html(data).fadeIn(500);
$("#send").removeAttr("disabled").attr("value", "send");
}
}
});
}
return false;
});
});
html:
<!-- Contact Form -->
<div class="row">
<div class="span12">
<div class="trac_contactform">
<form id="contact_form" class="row" name="form1" method="post" action="send.php">
<div class="span6">
<input type="text" class="full" name="name" id="name" placeholder="Name" />
<div id="error_name" class="error">Please check your name</div>
</div>
<div class="span6">
<input type="text" class="full" name="email" id="email" placeholder="Email" />
<div id="error_email" class="error">Please check your email</div>
</div>
<div class="span6">
<input type="text" class="full" name="mobile" id="mobile" placeholder="Phone Number"/>
</div>
<div class="span6">
<input type="text" class="full" name="subject" id="subject" placeholder="Subject"/>
</div>
<div class="span12">
<textarea cols="10" rows="10" name="message" id="message" class="full" placeholder="Message"></textarea>
<div id="error_message" class="error">Please check your message</div>
<div id="mail_success" class="success">Thank you. Your message has been sent.</div>
<div id="mail_failed" class="error">Error, email not sent</div>
<p id="btnsubmit">
<input type="submit" id="send" value="Send Now" class="btn btn-large btn-primary btn-embossed" /></p>
</div>
</form>
</div>
</div>
</div>
</div>
</section>
<!--END CONTACT PAGE-->
As Hanky 웃 Panky correctly pointed out you are not including the phone number to your email message. Try the following code. I stored the $_POST['message'] in a new variable called $sent_message and modified your $message variable to include the $subject, $sent_message and the $mobile variables.
<?php
$name = $_POST['name'];
$subject = $_POST['subject'];
$sender = $_POST['email'];
$sent_message = $_POST['message'];
$mobile = $_POST['mobile'];
$message = "Subject: " . $subject . "\r\n" . "Message: " . $sent_message . "\r\n" . "Phone number: " . $mobile;
$your_site_name = "www.krjwoodcraft.com";
$your_email = "rob.catharsis#gmail.com";
// setting header:
$header = "MIME-Version: 1.0\r\n";
$header .= "Content-type: text/html; charset=utf-8\r\n";
$header .= "From: {$name} <{$sender}>\r\n";
// to subject message header
$result = mail($your_email, "Message from ".$your_site_name, nl2br($message), $header);
echo "Your Message has been sent";
?>
You did not include it in your mail body. you have passed mobile number in php file. You got the file but you don't use it in your mail body.
include mobile number :
$result = mail($your_email, "Message from ".$your_site_name, nl2br($message."\r\n" . "Phone number: " . $mobile), $header);

I'm getting a 500 internal server error with my PHP contact form

I have a PHP contact form here:
leongaban.com
Below is a screenshot showing the 500 (Internal Server Error) I'm getting after I click Submit
HTML form
<div class="the-form">
<form id="contact">
<div id="status"></div>
<div>
<label for="name">Your Name</label>
<input type="text" name="name" id="name" value="" tabindex="1">
</div>
<div>
<label for="email">Your Email</label>
<input type="text" name="email" id="email" value="" tabindex="2">
</div>
<div>
<label for="textarea">Message:</label>
<textarea cols="40" rows="8" name="comments" id="comments" tabindex="3"></textarea>
</div>
<div>
<input class="submit-button" id="submit" type="submit" value="Submit" tabindex="5">
</div>
</form><!-- #contact -->
</div><!-- .the-form -->
My Javascript
$(function(){
$('#submit').click(function(){
var form_data = {
name: $('#name').val(),
email: $('#email').val(),
comments: $('#comments').val()
};
$.ajax({
url: "includes/send.php",
type: 'POST',
data: form_data,
success: function(status) {
if (status == 'success') {
$('#status').html('<h3 class="success">Thank You!</h3>')
.hide().fadeIn(2000);
} else {
$('#status').html('<p class="error">Both name and email are required fields.</p>')
.hide().fadeIn(2000);
}
} // end send contact form
}); //end ajax
return false;
}); //end send contact form click
});
My PHP
<?php
$name = $_POST['name'];
$email = trim($_POST['email']);
$comments = $_POST['comments'];
$error = array();
$site_owners_email = 'myEmail#gmail.com'; // Replace this with your own email address
$site_owners_name = 'Leon Gaban'; // replace with your name
if (strlen($name) < 2) {
$error['name'] = "Please enter your name.";
}
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.";
}
if (!$error) {
$response = 'success';
$subject = $name . ' needs help from CodePopper!';
$body = 'Codepopper,' . "\n\nName: " . $name .
"\nEmail: " . $email .
"\nComments: " . $comments;
require_once 'lib/swift_required.php';
$transport = Swift_SmtpTransport::newInstance('hostname', 25)
->setUsername('username')
->setPassword('password')
;
$mailer = Swift_Mailer::newInstance($transport);
$message = Swift_Message::newInstance();
$message->setSubject($subject);
$message->setFrom(array('myEmail#gmail.com' => 'leongaban.com'));
$message->setTo(array('myEmail#gmail.com' => 'Leon Gaban'));
$message->setBody($body);
$result = $mailer->send($message);
echo $response;
} # end if no error
else {
$response = 'error';
echo $response;
} # end if there was an error sending
I forgot to enter in my email host settings into my send.php file
$transport = Swift_SmtpTransport::newInstance('leongaban.com', 25)
->setUsername('my email')
->setPassword('my password');
Side note, I now have root access to my server :)

PHP/AJAX Mail Contact Form - part of the email message not showing up

Okay so I have a form that is using PHP to mail to an e-mail address. I also have a jQuery/AJAX section that validates the form without reloading the page and executes the PHP. For some reason the Product Interest value from the interest drop down is not coming through in the e-mail. What am I missing? I've been driving myself mad with this. Thanks!
This is the form:
<div class="contact-form">
<div class="row">
<div class="field"><input type="text" id="first" name="first" class="input" placeholder="First Name"></div>
<div class="field"><input type="text" id="last" name="last" class="input" placeholder="Last Name"></div>
<div class="field"><input type="text" id="telephone" name="telephone" class="input" placeholder="Phone Number"></div>
</div>
<div class="row">
<div class="field"><input type="email" id="email" name="email" class="input" placeholder="E-mail"></div>
<div class="field">
<select class="select" name="interest" id="interest">
<optgroup label="Countwise Products:">
<option value="I-Count">I-Count</option>
<option value="Q-Count">Q-Count</option>
<option value="D-Count">D-Count</option>
<option value="Z-Count">Z-Count</option>
</optgroup>
</select>
</div>
<input type="submit" value="Get Better Results!" class="button3 dark-blue submit"/>
<span class="error" style="display:none">All Fields Are Required!</span>
<span class="success" style="display:none">Contact Form Submitted Successfully</span>
</div>
</div>
</form>
This is the PHP for titled header_form_email.php
<?php
// POST Variables
//Name
$first = $_POST['first'];
$last = $_POST['last'];
//Phone
$telephone = $_POST['telephone'];
//E-mail
$email = $_POST['email'];
//Interest
$interest= $_POST['interest'];
// Contact subject
$subject = "CountWise Website - Sales Request";
$name = "$first" . " " . "$last";
$message = "You have received a new information request from Countwise.com\n".
"Name: " . "$name\n".
"Phone: " . "$telephone\n".
"Email: " . "$email\n".
"Product Interest: " . "$interest";
// From
$mailheader = "From: $email \r\n";
// Enter your email address
$to ="kelly#drastikdesigns.com";
$send_contact=mail($to,$subject,$message,$mailheader);
// Check, if message sent to your email
if($send_contact){
echo "<strong>We have received your information and will be in contact you shortly. Thank you.</strong>" ;
}
else {
echo "ERROR";
}
?>
This is the AJAX
$(function() {
$(".submit").click(function() {
var first = $("#first").val();
var last = $("#last").val();
var telephone = $("#telephone").val();
var email = $("#email").val();
var interest = $("#interest").val();
var dataString = 'first=' + first + '&last=' + last + '&telephone=' + telephone + '&email=' + email + '&interest' + interest;
if (first == '' || last == '' || telephone == '' || email == '') {
$('.success').fadeOut(200).hide();
$('.error').fadeOut(200).show();
}
else {
$.ajax({
type: "POST",
url: "http://www.drastikdesigns.com/clients/countwise/php/header_form_email.php",
data: dataString,
success: function() {
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
}
});
}
return false;
});
});
You forgot the equals:
'&interest=' + interest;
On a side note, why not just do:
data:$("#formid").serialize(),
That will save you tons of time and headache. Second point, using firebug/developers tools/chrome definitely helps when it comes to viewing the headers sent via ajax.

Categories