I'm trying use honeypot technique for my custom form on wordpress site.
My form look like that.
<form id="form-1"
action="<?php echo get_template_directory_uri(); ?>/mail.php" method="post" class="order__form form">
<p class="form__title">Order and Receive 30% off</p>
<p class="form__text">fill out this form so you can get sale</p>
<input type="text" name="name" class="form__item" placeholder="Your name">
<input type="email" name="email" required class="form__item" placeholder="Email address">
<p class="robotic" id="pot">
<label>If you're human leave this blank:</label>
<input name="robotest" type="text" id="robotest" class="robotest" />
</p>
<input type="submit" value="Send" class="button form__button">
</form>
Input with name robotest for validation on server side.
This is mail.php code:
<?php
$mess = '';
$mess .= '<hr>';
if($_POST['robotest'] != ''){
$error = "You are a gutless robot.";
} else {
if(isset($_POST['name'])) {
$name = substr(htmlspecialchars(trim($_POST['name'])), 0, 100);
$mess .= '<b>Имя отправителя: </b>' . $name . '<br>';
}
if(isset($_POST['email'])) {
if($_POST['email']!=''){
$email = substr(htmlspecialchars(trim($_POST['email'])), 0, 100);
$mess .= '<b>E-mail: </b>' . $email . '<br>';
}
}
}
$mess .= '<b>Заявка пришла со страницы:</b> ' . $_SERVER["HTTP_REFERER"] .'<br>';
$mess .= '<hr>';
require 'class.phpmailer.php';
$mail = new PHPMailer();
$mail->AddAddress('xxx2xxx.com','');
$mail->IsHTML(true);
$mail->CharSet = "UTF-8";
$mail->Subject = "new";
$mail->From = "new";
$mail->FromName = "new";
$mail->Body = $mess;
if ($mail->Send()) {
header('Location: ../');
} else {
die ('Mailer Error: ' . $mail->ErrorInfo);
}
header("Location: /thanks/");
?>
When I add validation for robotest, this script doesn't work.
You are setting the $error variable but you are not using it anywhere.
If you change the:
$error = "You are a gutless robot.";
To a:
die( "You are a gutless robot." );
You will have what you describe you want to have.
Related
The code below used to work fine a while ago, sending emails with images to Blogger's email; or sending emails to any provided email address. Unfortunately I have no idea when it stopped working and how to fix it. The error given is
Array ( [type] => 2 [message] => preg_match() expects parameter 2 to be string, array given [file] => /var/www/html/PHPMailer.php [line] => 4533 )
Below is the page, I appreciate if someone could fix it.
<?php
// error_reporting(0);
// ini_set('display_errors', 0);
var_dump($_POST["name"]);
var_dump($_POST["age"]);
var_dump($_FILES);
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
$error = '';
$name = '';
$age = '';
$email = '';
$subject = '';
$country = '';
$message = '';
$msg = '';
$youtube = '';
function clean_text($string)
{
$string = trim($string);
$string = stripslashes($string);
$string = htmlspecialchars($string);
return $string;
}
if(isset($_POST["submit"]))
{
if(empty($_POST["name"]))
{
$error .= '<p><label class="text-danger">Please Enter your Name</label></p>';
}
else
{
$name = clean_text($_POST["name"]);
if(!preg_match("/^[a-zA-Z ]*$/",$name))
{
$error .= '<p><label class="text-danger">Only letters and white space allowed</label></p>';
}
}
//age
if(empty($_POST["age"]))
{
$error .= '<p><label class="text-danger">Please Enter your Age</label></p>';
}
else
{
$age = clean_text($_POST["age"]);
if(!preg_match("/^[0-9]*$/",$age))
{
$error .= '<p><label class="text-danger">Only numbers allowed</label></p>';
}
}
//age
//i am
if(empty($_POST['formGender']))
{
$error .= '<p><label class="text-danger">Select your gender</label></p>';
}
//i am
//looking for
if(empty($_POST['formGender2']))
{
$error .= '<p><label class="text-danger">Select your Partner</label></p>';
}
//looking for
//for
if(empty($_POST['formGender3']))
{
$error .= '<p><label class="text-danger">Select your preferences</label></p>';
}
//for
if(empty($_POST["email"]))
{
$error .= '<p><label class="text-danger">Please Enter your Email</label></p>';
}
else
{
$email = clean_text($_POST["email"]);
if(!filter_var($email, FILTER_VALIDATE_EMAIL))
{
$error .= '<p><label class="text-danger">Invalid email format</label></p>';
}
}
if(empty($_POST["subject"]))
{
$error .= '<p><label class="text-danger">City/Town is required</label></p>';
}
else
{
$subject = clean_text($_POST["subject"]);
}
//country
if(empty($_POST["country"]))
{
$error .= '<p><label class="text-danger">Country is required</label></p>';
}
else
{
$subject = clean_text($_POST["country"]);
}
//country
if(empty($_POST["youtube"]))
{
// $error .= '<p><label class="text-danger">Please Enter your Name</label></p>';
}
else
{
$youtube = clean_text($_POST["youtube"]);
}
if(empty($_POST["message"]))
{
$error .= '<p><label class="text-danger">Message is required</label></p>';
}
else
{
$message = clean_text($_POST["message"]);
}
if(empty($_POST["phone"]))
{
// $error .= '<p><label class="text-danger">Message is required</label></p>';
}
else
{
$phone = clean_text($_POST["phone"]);
}
if($error == '')
{
if (array_key_exists('userfile', $_FILES)) {
if (isset($_SERVER["HTTP_CF_CONNECTING_IP"])) {
$_SERVER['REMOTE_ADDR'] = $_SERVER["HTTP_CF_CONNECTING_IP"];
}
$ip = $_SERVER['REMOTE_ADDR'];
require 'Exception.php';
require 'PHPMailer.php';
require 'SMTP.php';
$mail = new PHPMailer;
$mail->IsSMTP(); //Sets Mailer to send message using SMTP
$mail->Host = 'smtp.gmail.com'; //Sets the SMTP hosts
$mail->Port = '465'; //Sets the default SMTP server port
$mail->SMTPAuth = true; //Sets SMTP authentication. Utilizes the Username and Password variables
$mail->Username = 'asdfdfgndfbgasdf'; //Sets SMTP username
$mail->Password = 'asdfsgdbfsfg'; //Sets SMTP password
$mail->SMTPSecure = 'ssl'; //Sets connection prefix. Options are "", "ssl" or "tls"
$mail->From = $_POST["email"]; //Sets the From email address for the message
$mail->FromName = $_POST["name"]; //Sets the From name of the message
$mail->AddAddress('asdfasdf.dfnghdfghfgh#blogger.com', 'Name');//Adds a "To" address
$mail->AddCC($_POST["email"], $_POST["name"]); //Adds a "Cc" address
$mail->WordWrap = 1000; //Sets word wrapping on the body of the message to a given number of characters
$mail->IsHTML(true); //Sets message type to HTML
$mail->Subject = $_POST["name"] . ', ' . $_POST['formGender'] . ' (' . $_POST["age"] . ') looking to ' . $_POST["formGender3"] . ' in ' . $_POST["subject"] . ' ' . $_POST["country"]; //Sets the Subject of the message
if(empty($_POST["youtube"]))
{
$mail->Body = '<div id="intro"> Meet <span style="text-transform: capitalize;">' . $_POST["name"] . '</span>, a ' . $_POST["age"] . ' yo ' . $_POST["formGender"] . ' looking for ' . $_POST["formGender2"] . ' to ' . $_POST["formGender3"] . ' in ' . $_POST["subject"] . ' ' . $_POST["country"] . '. If you want to ' . $_POST["formGender3"] . ' in ' . $_POST["subject"] . ', ' . $_POST["country"] . ', leave a message for ' . $_POST["name"] . ' on this page or use the contact details below.<br/><br/><strong>Email</strong> ' . $_POST["email"] . ' <br/><strong>Phone</strong> ' . $_POST["phone"] . '.</div><div id="beforeblock">... more about ' . $_POST["name"] . ' below, in their own words: </div><div style="clear:both;"></div><blockquote>' . $_POST["message"] . '</blockquote><div id="regip">Profile registered from IP <strong>' . $ip . '</strong></div><iframe width="600" height="500" id="gmap_canvas" src="https://maps.google.com/maps?q=' . $_POST['subject'] . ',' . $_POST['country'] . '&t=&z=10&ie=UTF8&iwloc=&output=embed" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" loading="lazy" style="width:100%;max-width:100%;height:auto;min-height:315px;"></iframe><br/><span id="tags">' . $_POST['formGender'] . ', ' . $_POST['subject'] . ', ' . $_POST['country'] . '</span>'; //An HTML or plain text message body
}
if($_POST["youtube"])
{
$mail->Body = '<div id="intro"> Meet <span style="text-transform: capitalize;">' . $_POST["name"] . '</span>, a ' . $_POST["age"] . ' yo ' . $_POST["formGender"] . ' looking for ' . $_POST["formGender2"] . ' to ' . $_POST["formGender3"] . ' in ' . $_POST["subject"] . ' ' . $_POST["country"] . '. If you want to ' . $_POST["formGender3"] . ' in ' . $_POST["subject"] . ', ' . $_POST["country"] . ', leave a message for ' . $_POST["name"] . ' on this page or use the contact details below.<br/><br/><strong>Email</strong> ' . $_POST["email"] . ' <br/><strong>Phone</strong> ' . $_POST["phone"] . '.</div><div id="beforeblock">... more about ' . $_POST["name"] . ' below, in their own words: </div><div style="clear:both;"></div><blockquote>' . $_POST["message"] . '</blockquote><iframe loading="lazy" style="width:100%;min-height:315px;height:auto;margin:0 5px;" width="560" height="315" src="https://www.youtube.com/embed/' . $_POST["youtube"] . '" title="Video" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" id="youtubeframe" allowfullscreen></iframe><div id="regip">Profile registered from IP <strong>' . $ip . '</strong></div><iframe width="600" height="500" id="gmap_canvas" src="https://maps.google.com/maps?q=' . $_POST['subject'] . ',' . $_POST['country'] . '&t=&z=10&ie=UTF8&iwloc=&output=embed" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" loading="lazy" style="width:100%;max-width:100%;height:auto;min-height:200px;"></iframe><br/><span id="tags">' . $_POST['formGender'] . ', ' . $_POST['subject'] . ', ' . $_POST['country'] . '</span>'; //An HTML or plain text message body
}
$mail->set('X-Priority', '3'); //Priority 1 = High, 3 = Normal, 5 = low
//photo
//Attach multiple files one by one
for ($ct = 0, $ctMax = count($_FILES['userfile']['tmp_name']); $ct < $ctMax; $ct++) {
//Extract an extension from the provided filename
$ext = PHPMailer::mb_pathinfo($_FILES['userfile']['name'], PATHINFO_EXTENSION);
//Define a safe location to move the uploaded file to, preserving the extension
$uploadfile = tempnam(sys_get_temp_dir(), hash('sha256', $_FILES['userfile']['name'][$ct])) . '.' . $ext;
$filename = $_FILES['userfile']['name'][$ct];
if (move_uploaded_file($_FILES['userfile']['tmp_name'][$ct], $uploadfile)) {
if (!$mail->addAttachment($uploadfile, $filename)) {
$msg .= 'Failed to upload the photos ' . $filename;
}
} else {
$msg .= 'Failed to move photo to ' . $uploadfile;
}
}
// $mail->AddAttachment($image_location);
//photos
if($mail->Send()) //Send an Email. Return true on success or false on error
{
$error = '<label class="text-success">Thank you for registering your profile. It will be visible soon after aproval.</label><style>.form-container {display:none!important;}</style>';
}
else
{
$error = '<label class="text-danger">Your profile was not registered. Please try again!</label>';
// $errorMessage = error_get_last()['message'];
// echo $errorMessage;
// var_dump($_FILES);
print_r(error_get_last());
}
$name = '';
$age = '';
$email = '';
$subject = '';
$country = '';
$message = '';
$msg = '';
$youtube = '';
} //if img check ends
} //if error ends
}
?>
<!DOCTYPE html>
<html>
<head>
<style>
.form-container{width:96%;MAX-WIDTH:96%;margin:0 2%;}
.form-group{margin-bottom:10px}
.btn{background:#1c94ff;padding:4px 8px;border:none;box-shadow:2px 1px 1px #d3d3d3;color:#fff;outline:0;font-size:17px;cursor:pointer;width:100%}
label{display:block;margin-bottom:2px}
.form-group .form-control{width:100%;outline:0;padding:5px;border:none;background:#d1d1d1;border-bottom:2px solid #1c94ff;font-size:16px}
.has-success .form-control{border-bottom:2px solid #168b3f}
.has-danger .form-control{border-bottom:2px solid #dc1d34}
.form-group .text-help{color:#dc1d34}
.inline-label label{display:inline}
.pristine-error{display:table}
</style>
<script src="//ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script type="text/javascript">
if (typeof jQuery == 'undefined'){
document.write(unescape("%3Cscript src='//cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.slim.min.js' type='text/javascript'%3E%3C/script%3E"));
}
</script>
</head>
<body>
<?php echo $error; ?>
<div style="float:right;font-style: italic;"><span style="color:red;font-style: normal;">!</span> = mandatory</div>
<div class="form-container">
<form method="post" enctype="multipart/form-data" id="registercafebar">
<div class="form-group">
<label><span style="color:red">!</span> Name</label>
<input type="text" name="name" required minlength="3" maxlength="20" placeholder="Enter Your Name" class="form-control" value="<?php echo $name; ?>" />
</div>
<div class="form-group">
<label><span style="color:red">!</span> Age</label>
<input required type="number" minlength="2" maxlength="2" min="16" max="99" name="age" placeholder="Enter your real age" class="form-control" value="<?php echo $age; ?>" />
</div>
<div class="form-group">
<label><span style="color:red">!</span> I am a</label>
<select required name="formGender" class="form-control">
<option value="">Select your gender at birth</option>
<option value="woman">Woman</option>
<option value="man">Man</option>
</select>
</div>
<div class="form-group">
<label><span style="color:red">!</span> Looking for a</label>
<select name="formGender2" required class="form-control">
<option value="">Select who you are looking for</option>
<option value="man">Man</option>
<option value="woman">Woman</option>
<option value="couples">Couple</option>
</select>
</div>
<div class="form-group">
<label><span style="color:red">!</span> For</label>
<select name="formGender3" required class="form-control">
<option value="">Select what your intentions are</option>
<option value="date">Dating</option>
<option value="chat">Chat</option>
<option value="marry">Marriage</option>
<option value="have sex">Sex</option>
</select>
</div>
<div class="form-group">
<label><span style="color:red">!</span> City</label>
<input type="text" name="subject" required class="form-control" minlength="2" maxlength="25" placeholder="Enter your City/Town" value="<?php echo $subject; ?>" />
</div>
<div class="form-group">
<label><span style="color:red">!</span> Country</label>
<input type="text" name="country" required class="form-control" minlength="2" maxlength="20" placeholder="Enter your Country" value="<?php echo $country; ?>" />
</div>
<div class="form-group">
<label><span style="color:red">!</span> About me </label>
<textarea name="message" cols="30" rows="5" minlength="200" maxlength="1000" required class="form-control" placeholder="Describe who you are and what you are looking for, write about the things you like or dislike or talk about your hobbies, but keep it spam free."><?php echo $message; ?></textarea>
</div>
<div class="form-group">
<label><span style="color:red">!</span> Email</label>
<input type="email" name="email" class="form-control" minlength="6" maxlength="30" required placeholder="Enter Your Email" value="<?php echo $email; ?>" />
</div>
<div class="form-group">
<label>Phone</label>
<input type="number" name="phone" class="form-control" minlength="4" maxlength="25" placeholder="Enter Your Phone" value="<?php echo $phone; ?>" />
</div>
<div class="form-group">
<label>Youtube video ID <br/><span style="text-decoration: line-through;">https://www.youtube.com/watch?v=</span><strong style="padding:0 5px;border:1px solid gray;">fhgnfyhfth</strong></label>
<input type="text" name="video" class="form-control" minlength="5" maxlength="15" placeholder="Enter Your Youtube video" value="<?php echo $youtube; ?>" />
</div>
<div class="form-group">
<input type="hidden" name="MAX_FILE_SIZE" value="10000000">
<span style="color:red">!</span> Photos:
<input name="userfile[]" required type="file" multiple="multiple" accept="image/*">
</div>
<div id="message"><span style="color:red">!</span> Please verify:</div>
<div id="success">Perfect ✓</div>
<div id="fail"><span style="color:red">!</span> Try again</div>
<p id="question"></p> <input id="ans" type="text">
<p><span style="color:red">!</span> Are you human?<br/> No <input type="checkbox" name="no"> Yes <input type="checkbox" name="yes" required></p>
<script>
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires="+d.toUTCString();
document.cookie = cname + "=" + cvalue + "; " + expires;
}
</script>
<div class="form-group inline-label">
<span style="color:red">!</span> <input id="ch1" type="checkbox" name="future" required data-pristine-required-message="You must accept the terms and conditions"/>
<label for="ch1">I accept the terms and conditions</label><br/>
</div>
<div class="form-group">
<input type="submit" name="submit" value="Register" class="btn btn-info" disabled="disabled" /><!--disabled="disabled"-->
</div>
</form>
</div>
<div class="timer" onload="timer(1800)">
<div class="time">
<strong>Time until the page will refresh: <span id="time">Loading...</span></strong>
</div>
</div>
<br/>
<script>
var total;
function getRandom() {
return Math.ceil(Math.random() * 20);
}
function createSum() {
var randomNum1 = getRandom(),
randomNum2 = getRandom();
total = randomNum1 + randomNum2;
jQuery("#question").text(randomNum1 + " + " + randomNum2 + "=");
jQuery("#ans").val('');
checkInput();
}
function checkInput() {
var input = jQuery("#ans").val(),
slideSpeed = 200,
hasInput = !!input,
valid = hasInput && input == total;
jQuery('#message').toggle(!hasInput);
jQuery('input[type=submit]').prop('disabled', !valid);
jQuery('#success').toggle(valid);
jQuery('#fail').toggle(hasInput && !valid);
}
jQuery(document).ready(function() {
//create initial sum
createSum();
// On "reset button" click, generate new random sum
jQuery('input[type=reset]').click(createSum);
// On user input, check value
jQuery("#ans").keyup(checkInput);
//cookie registered
});
</script>
</body>
</html>
If it matters, I am using PHP 7.3, NginX. From my knowledge, same config as when the script used to work.
Also tried this:
Adding the following right after <?php, following the comments
var_dump($_POST["name"]);
var_dump($_POST["age"]);
var_dump($_FILES);
Returns this before submitting the form:
NULL NULL array(0) { }
And this after submitting the form:
string(14) "Johny macaroni" string(2) "22" array(1) { ["userfile"]=> array(5) { ["name"]=> array(1) { [0]=> string(8) "oslo.png" } ["type"]=> array(1) { [0]=> string(9) "image/png" } ["tmp_name"]=> array(1) { [0]=> string(14) "/tmp/phpen1nVm" } ["error"]=> array(1) { [0]=> int(0) } ["size"]=> array(1) { [0]=> int(28358) } } }
In the end, the problem was not related to my script at all. It was the Gmail and Outlook SMTP services that, for some reason, refused to honor the script's SMTP requests; both of them.
So, after switching to a 3rd free SMTP provider, everything started to work as it did before. Solved.
There are quite a few nonsensical things in here. It looks like you've adapted this from a very old example.
The require statements inside the function mean that this will crash the second time you call the function.
You're preprocessing the email address into $email but not using that variable when actually setting the recipient.
You're forging the from address, which is likely to mean your messages will not be delivered.
Sending a copy to the supposed sender means your script is a spam gateway that can be abused to send arbitrary content to arbitrary recipients. This is bad and will be mercilessly exploited by spammers.
Port is an integer, not a string:
$mail->Port = 465;
This will do nothing useful:
$mail->set('X-Priority', '3');
If you want to add a custom header, use addCustomHeader. If you want to set a priority, set the Priority property, which is also an int:
$mail->Priority = 3;
Overall, base your code on the examples provided, particularly the contact form example.
Update
Now that we have a location for the error, we can see that it's in the call to PHPMailer::mb_pathinfo, which passes in $_FILES['userfile']['name'] as the $path parameter, and not in addCC as I had guessed. The HTML form declares this input as an array of file type allowing multiple values:
<input name="userfile[]" required type="file" multiple="multiple" accept="image/*">
This means that $_FILES['userfile']['name'] will be an array, not a string (see the PHP docs), which is the cause of the error.
The fix here is to get the name property of the individual file, not the array of all of them, which is done by adding the array index, so this line:
$ext = PHPMailer::mb_pathinfo($_FILES['userfile']['name'], PATHINFO_EXTENSION);
should be:
$ext = PHPMailer::mb_pathinfo($_FILES['userfile']['name'][$ct], PATHINFO_EXTENSION);
This bug was previously present in the example code that this was originally adapted from, though that was fixed 6 months ago.
For my WordPress (v5.5.1) I am using Bootstrap and built a Custom Contact Form in Bootstrap Modal with below HTML (followed this tutorial: https://premium.wpmudev.org/blog/how-to-build-your-own-wordpress-contact-form-and-why/).
<form id="contact-form" action="<?php echo get_site_url(); ?>" method="post">
<div class="modal-body">
<?php echo $response; ?>
<div class="form-group">
<input class="form-control my-2" type="text" name="message_name" size="50" placeholder="Your full name" value="<?php echo esc_attr($_POST['message_name']); ?>">
<input class="form-control my-2" type="email" name="message_email" size="50" placeholder="Email address" value="<?php echo esc_attr($_POST['message_email']); ?>">
<input class="form-control my-2" type="tel" name="message_tel" size="50" placeholder="Country code, Phone number" value="<?php echo esc_attr($_POST['message_tel']); ?>">
<textarea class="form-control my-2" name="message_text" rows="2" placeholder="Your message" value="<?php echo esc_attr($_POST['message_text']); ?>"></textarea>
<input class="form-control my-2" type="text" name="message_human" placeholder="Human check: Enter 2">
<input type="hidden" name="message_url" value="<?php the_permalink(); ?>">
<input type="hidden" name="message_page" value="<?php the_title(); ?>">
</div>
</div>
<div class="modal-footer">
<input type="hidden" name="submitted" value="1">
<button type="submit" value="Submit" class="btn btn-search form-control">Send Enquiry</button>
</div>
Below the function to validate the Forms & show responses while Form submission:
function validateform() {
//response generation function
$response = "";
//function to generate response
function contact_g_form_response($type, $message) {
global $response;
if ($type == "success") {
$response = "<div class='message-success text-center'>{$message}</div>";
} else {
$response = "<div class='message-error text-center'>{$message}</div>";
}
}
//response messages
$not_human = "Enter current year in numbers.";
$missing_content = "Missing something.";
$email_invalid = "Check your Email address.";
$message_unsent = "Message was not sent. Try Again.";
$message_sent = "Thanks! We got your enquiry.";
//user posted variables
$name = $_POST['message_name'];
$email = $_POST['message_email'];
$fromEmail = $name . '<' . $email . '>';
$tel = $_POST['message_tel'];
$text = $_POST['message_text'];
$url = $_POST['message_url'];
$page = $_POST['message_page'];
$human = $_POST['message_human'];
//php mailer variables
$to = get_option('admin_email');
$subject = '[General Enquiry] ' . $name . ' | Phone Number:' . $tel;
$headers = 'From: ' . $fromEmail . "\r\n" .
'Reply-To: ' . $email . "\r\n";
$message = '<html><body><h1>New general enquiry from ' . $name . '!</h1>'
. '<p>Email: ' . $email . '</p>'
. '<p>Phone Number: ' . $tel . '</P>'
. '<p>Inquiry: ' . $text . '</P>'
. '<p>From page: <b>' . $page . '</b></P>'
. '<p>Page URL: ' . $url . '</p>'
. '</body></html>';
if (!$human == 0) {
if ($human != 2) {
contact_g_form_response("error", $not_human); //not human!
} else {
//validate email
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
contact_g_form_response("error", $email_invalid);
} else { //email is valid
//validate presence of name, phone number
if (empty($name) || empty($tel)) {
contact_g_form_response("error", $missing_content);
} else { //ready to go!
$sent = wp_mail($to, $subject, $message, implode("\r\n", $headers)); //mail to admin - striptags removing formatting
// $sent2 = wp_mail($email, $subject, $body, $headers); //mail to visitor
// if ($sent || $sent2) {
if ($sent) {
contact_g_form_response("success", $message_sent); //message sent!
} else {
contact_g_form_response("error", $message_unsent); //message wasn't sent
}
}
}
}
} else if ($_POST['submitted']) {
contact_g_form_response("error", $missing_content);
}
}
In the earlier versions of WordPress the email was being sent without validation, with v5.5.1 upgrade, the Modal is closing without any validation and the email is also not being sent.
You Just Need To replace this:
<form id="contact-form" action="<?php echo get_site_url();?>" method="post">
With This:
<form id="contact-form" method="post">
Because You are displaying the error on the same page but on click of the submit button the action is taking you to a specific url and that's the reason the validations are not shown.
And This:
if ($type == "success") {
$response = "<div class='message-success text-center'>{$message}</div>";
} else {
$response = "<div class='message-error text-center'>{$message}</div>";
}
With This also:
if ($type == "success") {
$response = $message;
echo $response;
} else {
$response = $message;
echo $response;
}
I can't seem to figure out why my php isn't sending the name and phone number to the email. Email and message is working fine.
Here is my HTML:
<form method="POST" name="contact_form" action="php.php">
<label for='fname'>Name: </label>
<input type="text" name="fname">
<label for='email'>Email: </label>
<input type="text" name="email">
<label for='phone'>Phone: </label>
<input type="text" name="phone">
<label for='message'>Message:</label>
<textarea name="message" rows=8 cols=30><?php echo htmlentities($user_message) ?></textarea>
<label><img src="/captcha.php"></label>
<input type="text" name="code" value="Please enter the code"> <br />
<input type="submit" value="Submit" name='submit' class="quoteButton">
</form>
Here is my PHP:
session_start();
if (isset($_POST['submit'])) {
$error = "";
if (!empty($_POST['fname'])) {
$name = $_POST['fname'];
} else {
$error .= "You didn't type in your name. <br />";
}
if (!empty($_POST['phone'])) {
$name = $_POST['phone'];
} else {
$error .= "You didn't enter your phone. <br />";
}
if (!empty($_POST['email'])) {
$email = $_POST['email'];
if (!preg_match("/^[a-z0-9]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i", $email)){
$error .= "The e-mail address you entered is not valid. <br/>";
}
} else {
$error .= "You didn't type in an e-mail address. <br />";
}
if (!empty($_POST['message'])) {
$message = $_POST['message'];
} else {
$error .= "You didn't type in a message. <br />";
}
if(($_POST['code']) == $_SESSION['code']) {
$code = $_POST['code'];
} else {
$error .= "The captcha code you entered does not match. Please try again. <br />";
}
if (empty($error)) {
$from = 'From: ' . $fname . ' <' . $email . '>';
$to = "mail#domain.com";
$subject = "New contact form message";
$content = $fname . " has sent you a message. \nEmail: $email \nPhone: $phone \nMessage: \n" . $message;
$success = header( 'Location: '' ) ;
mail($to,$subject,$content,$from);
}
}
?>
Any help would be greatly appreciated. Thanks!
1)You named the variable for first name $name but use $fname in the email portion of code
$name = $_POST['fname'];
should be
$fname = $_POST['fname'];
2) You named the variable for first name $name (overwriting your initial assignment) but use $phone in the email portion of code
$name = $_POST['phone'];
should be
$phone = $_POST['phone'];
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
My contact form will not submit and send to my email address..
Here is the PHP validation I am using to check required fields and then to send to my email:
<?php
if (isset($_GET['submit'])) {
$body = '';
$body .= 'Name: ' . $_POST['name'] . "\n\n";
$body .= 'Phone: ' . $_POST['phone'] . "\n\n";
$body .= 'Email: ' . $_POST['email'] . "\n\n";
$body .= 'Message: ' . $_POST['message'] . "\n\n";
mail('myemailaddress#gmail.com', 'Contact Form', $body, 'From: no-reply#mycompany.com');
}
// define variables and initialize with empty values
$nameErr = $addressErr = $emailErr = $messageErr = $spamcheckErr = "";
$name = $address = $email = $message = $spamcheck = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Please enter your name.";
}
else {
$name = $_POST["name"];
}
if (empty($_POST["email"])) {
$emailErr = "Please enter your email.";
}
else {
$email = $_POST["email"];
}
if (empty($_POST["message"])) {
$messageErr = "Cannot leave message box blank.";
}
else {
$message = $_POST["message"];
}
if (!isset($_POST["spamcheck"])) {
$spamcheckErr = "Verify you are not spam.";
}
else {
$spamcheck = $_POST["spamcheck"];
}
}
?>
Here is my HTML:
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<div id="contact_input" class="col1">
<input name="name" placeholder="Name*" type="text" class="text" value="<?php echo htmlspecialchars($name);?>">
<span class="error"><?php echo $nameErr;?></span><br />
<input name="email" placeholder="Email*" type="email" class="text" value="<?php echo htmlspecialchars($email);?>">
<span class="error"><?php echo $emailErr;?></span><br />
<input name="phone" placeholder="Phone #" type="tel" class="text" value="<?php echo $phone;?>" />
</div>
<div id="contact_input" class="col2">
<textarea name="message" placeholder="Message*" rows="10" cols="25"><?php echo $message?></textarea>
<span class="error"><?php echo $messageErr;?></span>
</div>
<div id="contact_input" class="col3">
<input id="spamcheck" type="checkbox" name="spamcheck" value="<?php echo htmlspecialchars($spamcheck);?>">I am human.*<br />
<span class="error"><?php echo $spamcheckErr;?></span>
<input id="submit" type="submit" name="submit" value="Send" class="button" /><br />
<span>*Required Field.</span>
</div>
</form>
When fields are empty I get the proper error message under each field but I cannot get it to send to my email. However it was emailing me every time I loaded the page, when I made these changes it stopped submitting.
Being new to contact forms with required fields, I can't seem to find the clear answer elsewhere.
I suspect it has something to do with if (isset($_GET['submit'])) Since that is where I made the change and started having issues.
You have to add ?submit to the action string in your form or else $_GET['submit'] will be unset.
<form method="post" action="?submit">
or you can change the isset function to check the $_POST var instead of the $_GET var
if (isset($_POST['submit'])) {
EDIT: Here's what you should do with your validation script
if (!empty($_POST['submit'])) {
$error = array();
if (empty($_POST['email'])) $error[] = 'Please enter your email';
// and so on...
if (empty($error)) {
// Send email script goes here
}
}
And then for your user display upon any errors:
if (!empty($error)) foreach ($error as $e) echo '<p class="error">'.$e.'</p>';
This allows you to add more error messages as often as you'd like with ease, and uses the empty property of an array to verify the lack of error in validation.
I tested your code and everything checked out, except for this line:
if (isset($_GET['submit'])) {
which just needs to be changed to:
if (isset($_POST['submit'])) {
The issue was in fact using $_GET instead of $_POST
EDIT
Added a few conditional statements:
if (($_POST['name'] && $_POST['email'] && $_POST['message'] !="")
&& isset($_POST["spamcheck"]) !="")
Full code (use the full version below):
<?php
if (isset($_POST['submit'])) {
$body = '';
$body .= 'Name: ' . $_POST['name'] . "\n\n";
$body .= 'Phone: ' . $_POST['phone'] . "\n\n";
$body .= 'Email: ' . $_POST['email'] . "\n\n";
$body .= 'Message: ' . $_POST['message'] . "\n\n";
if (($_POST['name'] && $_POST['email'] && $_POST['message'] !="") && isset($_POST["spamcheck"]) !="")
{
mail('myemailaddress#gmail.com', 'Contact Form', $body, 'From: no-reply#mycompany.com');
}
}
// define variables and initialize with empty values
$nameErr = $addressErr = $emailErr = $messageErr = $spamcheckErr = "";
$name = $address = $email = $message = $spamcheck = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Please enter your name.";
}
else {
$name = $_POST["name"];
}
if (empty($_POST["email"])) {
$emailErr = "Please enter your email.";
}
else {
$email = $_POST["email"];
}
if (empty($_POST["message"])) {
$messageErr = "Cannot leave message box blank.";
}
else {
$message = $_POST["message"];
}
if (!isset($_POST["spamcheck"])) {
$spamcheckErr = "Verify you are not spam.";
}
else {
$spamcheck = $_POST["spamcheck"];
}
}
?>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<div id="contact_input" class="col1">
<input name="name" placeholder="Name*" type="text" class="text" value="<?php echo htmlspecialchars($name);?>">
<span class="error"><?php echo $nameErr;?></span><br />
<input name="email" placeholder="Email*" type="email" class="text" value="<?php echo htmlspecialchars($email);?>">
<span class="error"><?php echo $emailErr;?></span><br />
<input name="phone" placeholder="Phone #" type="tel" class="text" value="<?php echo $phone;?>" />
</div>
<div id="contact_input" class="col2">
<textarea name="message" placeholder="Message*" rows="10" cols="25"><?php echo $message?></textarea>
<span class="error"><?php echo $messageErr;?></span>
</div>
<div id="contact_input" class="col3">
<input id="spamcheck" type="checkbox" name="spamcheck" value="<?php echo htmlspecialchars($spamcheck);?>">I am human.*<br />
<span class="error"><?php echo $spamcheckErr;?></span>
<input id="submit" type="submit" name="submit" value="Send" class="button" /><br />
<span>*Required Field.</span>
</div>
</form>
I don't understndand if (isset($_GET['submit'])) in fact. Why is it there?
$field1 = NULL;
$field2 = NULL;
if(isset($_POST["submit"])){
$field1 = $_POST["field1"];
$field2 = $_POST["field2"];
//etc
mail ("youremail", "yoursubject", "$field1 $field2 $field3 etc.");
}
I'm not very familiar with PHP. In the past I have been able to read and fix small problems using PHP but this one is giving me quite lot of trouble.
I have a form with two entry boxes, one for email and one for message.
Now, Im trying to add another box to the form to verify human access for anti-spam purposes.
This is the code which I can't make the verification process go through.
//create ramdom numbers
<?php
$num1 = rand(0,9);
$num2 = rand(0,9);
?>
<?php
$error = '';
$email = '';
$comments = '';
$verify = '';
if(isset($_POST['contactus'])) {
$email = $_POST['email'];
$comments = $_POST['comments'];
$app = $_SERVER["REQUEST_URI"];;
if(trim($comments) == '') {
$error = '<div class="error_message">Attention! Please enter your message.</div>';
} else if(trim($email) == '') {
$error = '<div class="error_message">Attention! Please enter a valid email address.</div>';
} else if(!isEmail($email)) {
$error = '<div class="error_message">Attention! You have enter an invalid e-mail address, try again.</div>';
}
//This is where Im having problem. From this point the form doesn't go on.
if(trim($verify) == '') {
error( '<div class="error_message">Attention! Please enter the verification number.</div>');
} else if(trim($verify) != $verify_result) {
error( '<div class="error_message">Attention! The number you entered is incorrect.</div>');
}
if($error == '') {
if(get_magic_quotes_gpc()) {
$comments = stripslashes($comments);
}
$address = "info#myaddress.com";
$e_subject = 'You\'ve been contacted from an app web page ' . $name . '.';
$e_body = "You have been contacted using the app comments box on the above app web page, their additional message is as follows.\r\n\n";
$e_content = "\"$comments\"\r\n\n";
$e_reply = "$name $email";
$msg = $e_body . $e_content . $e_reply;
mail($address, $e_subject, $msg, $app, "From: $email\r\nReply-To: $email\r\nReturn-Path: $email\r\n");
// Email has sent successfully, echo a success page.
echo "<div id='success_page_apps'>";
echo "<h1>Email Sent Successfully.</h1>";
echo "<p>Thank you, your message has been submitted to us.</p>";
echo "</div>";
echo '<input type="button" value="Send Another" onClick="history.go(-1); return (true); ">';
}
}
if(!isset($_POST['contactus']) || $error != '') {
<?php echo $error; ?>
<fieldset id="contact_apps">
<form method="post" action="#ContactForm">
<label for="email" accesskey="E"><span class="required"></span> Email</label>
<input name="email" type="text" id="email" size="33" value="<?php echo$email;?>"/>
<textarea name="comments" cols="50" rows="15" id="comments"><?php echo$comments;?></textarea>
//This is the 'Are you human?' message
<p><span class="required">*</span> Are you human?</p>
<label class="numbersq" for='verify' accesskey='V'><?php echo $num1; ?> + <?php echo $num2; ?> =</label>
<input class="numbersa" name="verify" type="text" id="verify" size="4" value=""/>
<input name="verify_result" type="hidden" size="4" value="<?php echo $num1+$num2; ?>" /><br />
<input name="contactus" type="submit" class="send" id="contactus" >
</form>
</fieldset>
}
?>
Please note the 'Are you human' message and the conditionals I have in the script which is where I think I'm doing something wrong.
You've forgotten to pull the verify values from the form ... and you have a few other simple errors in there too which I've addressed.
//create ramdom numbers
<?php
$num1 = rand(0,9);
$num2 = rand(0,9);
?>
<?php
$error = '';
$email = '';
$comments = '';
$verify = '';
if(isset($_POST['contactus'])) {
$email = $_POST['email'];
$comments = $_POST['comments'];
$app = $_SERVER["REQUEST_URI"];;
if(trim($comments) == '') {
$error = '<div class="error_message">Attention! Please enter your message.
</div>';
} else if(trim($email) == '') {
$error = '<div class="error_message">Attention! Please enter a valid email address.
</div>';
} else if(!isEmail($email)) {
$error = '<div class="error_message">Attention! You have enter an invalid e-mail address, try again.</div>';
}
//This is where Im having problem. From this point the form doesn't go on.
$verify_result= $_POST['verify_result'];
$verify = $_POST["verify"];
if(trim($verify) == '') {
$error = '<div class="error_message">Attention! Please enter the verification number.</div>';
} else if(trim($verify) != $verify_result) {
$error = '<div class="error_message">Attention! The number you entered is incorrect.</div>';
}
if($error == '') {
if(get_magic_quotes_gpc()) {
$comments = stripslashes($comments);
}
$address = "info#myaddress.com";
$e_subject = 'You\'ve been contacted from an app web page ' . $name . '.';
$e_body = "You have been contacted using the app comments box on the above app web page, their additional message is as follows.\r\n\n";
$e_content = "\"$comments\"\r\n\n";
$e_reply = "$name $email";
$msg = $e_body . $e_content . $e_reply;
// mail($address, $e_subject, $msg, $app, "From: $email\r\nReply-To: $email\r\nReturn-Path: $email\r\n");
// Email has sent successfully, echo a success page.
echo "<div id='success_page_apps'>";
echo "<h1>Email Sent Successfully.</h1>";
echo "<p>Thank you, your message has been submitted to us.</p>";
echo "</div>";
echo '<input type="button" value="Send Another" onClick="history.go(-1); return (true); ">';
}
}
if(!isset($_POST['contactus']) || $error != '') {
echo $error; ?>
<fieldset id="contact_apps">
<form method="post" action="#ContactForm">
<label for="email" accesskey="E"><span class="required"></span> Email</label>
<input name="email" type="text" id="email" size="33" value="<?php echo$email;?>"/>
<textarea name="comments" cols="50" rows="15" id="comments"><?php echo$comments;?></textarea>
//This is the 'Are you human?' message
<p><span class="required">*</span> Are you human?</p>
<label class="numbersq" for='verify' accesskey='V'><?php echo $num1; ?> + <?php echo $num2; ?> =</label>
<input class="numbersa" name="verify" type="text" id="verify" size="4" value=""/>
<input name="verify_result" type="hidden" size="4" value="<?php echo $num1+$num2; ?>" /><br />
<input name="contactus" type="submit" class="send" id="contactus" >
</form>
</fieldset>
<?PHP
}
?>