Issues with php verification script - php

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
}
?>

Related

Change email address based on drop-down selection

I have a contact form with the following fields:
Name
Email
Number
Department
Message
"Department" is a drop down selection with the seven following options
Audio Engineering
Graphic Design
Music Production
Photography
Videography
Web Development
Other
I have been trying to set it up in such a way where the email address that the data is being sent to, changes based on the user's drop-down selection. For example, if the user selects Option 1, "Audio Engineering", the email will be sent to "audio#email.com". If the user selects Option 2, "Graphic Design", the email will be sent to "graphics#email.com" and so on, upon submission of the form. However, my current code returns an error.
This is my HTML.
<form method="post" action="contact.php" name="contactform" id="contactform">
<fieldset id="contact_form">
<label for="name">
<input type="text" name="name" id="name" placeholder="ENTER YOUR NAME">
</label>
<label for="email">
<input type="email" name="email" id="email" placeholder="ENTER YOUR EMAIL">
</label>
<label for="phone">
<input type="text" name="phone" id="phone" placeholder="PHONE NUMBER">
</label>
<label for="department">
<select name="department" id="department" class="cs-select cs-skin-border" required>
<option value="" disabled selected>DEPARTMENT</option>
<option value="audio">Audio Engineering</option>
<option value="graphics">Graphic Design</option>
<option value="music">Music Production</option>
<option value="photography">Photography</option>
<option value="videography">Videography</option>
<option value="development">Web Development</option>
<option value="other">Other</option>
</select>
</label>
<label for="comments">
<textarea name="comments" id="comments" placeholder="ENTER YOUR MESSAGE"></textarea>
</label>
<input type="submit" class="submit btn btn-default btn-black" id="submit" value="Submit">
</fieldset>
</form>
This is the snippet of my PHP where I use if statements to change emails based on selection.
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$dept = $_POST['department'];
$comments = $_POST['comments'];
if(trim($name) == '') {
echo '<div class="error_message" style="color: #de493e; font-weight: 700;">Please enter your name. Don\'t be shy!</div>';
exit();
} else if(trim($email) == '') {
echo '<div class="error_message" style="color: #de493e; font-weight: 700;">Please enter your email address, so we can get back to you!</div>';
exit();
} else if(!isEmail($email)) {
echo '<div class="error_message" style="color: #de493e; font-weight: 700;">Invalid e-mail address, try again!</div>';
exit();
} else if(trim($comments) == '') {
echo '<div class="error_message" style="color: #de493e; font-weight: 700;">You forgot to enter your message!</div>';
exit();
}
if($dept == "audio") {
$address = "audio#email.com";
} else if ($dept == "graphics") {
$address = "graphics#email.com";
} else if ($dept == "music") {
$address = "music#email.com";
} else if ($dept == "photography") {
$address = "photography#email.com";
} else if ($dept == "videography") {
$address = "videography#email.com";
} else if ($dept == "development") {
$address = "development#email.com";
} else if ($dept == "other") {
$address = "admin#email.com";
}
if(mail($address, $received_subject, $message, $header)) {
// Email has sent successfully, echo a success page.
echo "<h2>Email Sent Successfully.</h2>";
echo "<p>Thank you <strong>$name</strong>, your message has been sent to us.</p>";
echo "<p>We will get back to you within 24 hours!</p>";
} else {
echo '<h2>ERROR!</h2>';
}
?>
This unfortunately returns "ERROR!" and i'm not sure why.
I would also like to return an error message if no selection is made.
Passed param to mail function.
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$dept = $_POST['department'];
$comments = $_POST['comments'];
if(trim($name) == '') {
echo '<div class="error_message" style="color: #de493e; font-weight: 700;">Please enter your name. Don\'t be shy!</div>';
exit();
} else if(trim($email) == '') {
echo '<div class="error_message" style="color: #de493e; font-weight: 700;">Please enter your email address, so we can get back to you!</div>';
exit();
} else if(!isEmail($email)) {
echo '<div class="error_message" style="color: #de493e; font-weight: 700;">Invalid e-mail address, try again!</div>';
exit();
} else if(trim($comments) == '') {
echo '<div class="error_message" style="color: #de493e; font-weight: 700;">You forgot to enter your message!</div>';
exit();
}
if($dept == "audio") {
$address = "audio#email.com";
} else if ($dept == "graphics") {
$address = "graphics#email.com";
} else if ($dept == "music") {
$address = "music#email.com";
} else if ($dept == "photography") {
$address = "photography#email.com";
} else if ($dept == "videography") {
$address = "videography#email.com";
} else if ($dept == "development") {
$address = "development#email.com";
} else if ($dept == "other") {
$address = "admin#email.com";
}
$message = "First line of text\nSecond line of text";
$received_subject = "My subject";
if(mail($address, $received_subject, $message)) {
// Email has sent successfully, echo a success page.
echo "<h2>Email Sent Successfully.</h2>";
echo "<p>Thank you <strong>$name</strong>, your message has been sent to us.</p>";
echo "<p>We will get back to you within 24 hours!</p>";
} else {
echo '<h2>ERROR!</h2>';
}

WordPress custom Contact Form in Bootstrap modal is not showing validation & submission response

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;
}

Captcha Value is not reading while form submission

I came across a problem with PHP form submission. I'm not able to read the captcha filed value in form submission. Here is the code
HTML
<div class="container">
<h2 class="centertitle">Contact Us</h2>
<div id="message"></div>
<form method="post" action="php/contact.php" name="contactform" id="contactform">
<div class="row">
<div class="col-sm-3">
<input type="text" name="name" placeholder="Name" id="name" class="form-control" />
</div>
<div class="col-sm-3">
<input type="text" name="email" placeholder="Email" id="email" class="form-control" />
</div>
<div class="col-sm-3">
<input type="text" name="phone" placeholder="Phone" id="phone" class="form-control" />
</div>
<div class="col-sm-3">
<div id="captcha">
<input type="text" name="verify" id="verify" class="form-control" placeholder="Enter Captcha" />
<img src="php/image.php" alt="well, this is out capcha image" class="captcha" />
</div>
</div>
</div>
<div class="row">
<div class="col-sm-12 text-center">
<input type="submit" name="send" value="Submit" id="submit" class="sbtn" />
</div>
</div>
</form>
</div><!-- /.container -->
Js Validation
$(document).ready(function() {
//Form Validation
$('#contactform').submit(function(){
var action = $(this).attr('action');
$("#message").slideUp(750,function() {
$('#message').hide();
$('#submit')
//.after('<img src="images/ajax-loader.gif" class="loader" />')
.attr('disabled','disabled');
$.post(action, {
name: $('#name').val(),
email: $('#email').val(),
phone: $('#phone').val(),
subject: $('#subject').val(),
comments: $('#comments').val(),
verify: $('#verify').val()
},
function(data){
document.getElementById('message').innerHTML = data;
$('#message').slideDown('slow');
$('#contactform img.loader').fadeOut('slow',function(){$(this).remove()});
$('#submit').removeAttr('disabled');
if(data.match('success') != null) $('#contactform').slideUp('slow');
}
);
});
return false;
});
});
Contact.PHP
<?php
if(!$_POST) exit;
// Email address verification, do not edit.
function isEmail($email) {
return(preg_match("/^[-_.[:alnum:]]+#((([[:alnum:]]|[[:alnum:]][[:alnum:]-]*[[:alnum:]])\.)+(ad|ae|aero|af|ag|ai|al|am|an|ao|aq|ar|arpa|as|at|au|aw|az|ba|bb|bd|be|bf|bg|bh|bi|biz|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|com|coop|cr|cs|cu|cv|cx|cy|cz|de|dj|dk|dm|do|dz|ec|edu|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gh|gi|gl|gm|gn|gov|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|in|info|int|io|iq|ir|is|it|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|mg|mh|mil|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|museum|mv|mw|mx|my|mz|na|name|nc|ne|net|nf|ng|ni|nl|no|np|nr|nt|nu|nz|om|org|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|pro|ps|pt|pw|py|qa|re|ro|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)$|(([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5])\.){3}([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5]))$/i",$email));
}
if (!defined("PHP_EOL")) define("PHP_EOL", "\r\n");
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$verify = $_POST['verify'];
if(trim($name) == '') {
echo '<div class="error_message">Attention! You must enter your name.</div>';
exit();
} else if(trim($email) == '') {
echo '<div class="error_message">Attention! Please enter a valid email address.</div>';
exit();
} else if(trim($phone) == '') {
echo '<div class="error_message">Attention! Please enter a valid phone number.</div>';
exit();
} else if(!is_numeric($phone)) {
echo '<div class="error_message">Attention! Phone number can only contain digits.</div>';
exit();
} else if(!isEmail($email)) {
echo '<div class="error_message">Attention! You have entered an invalid e-mail address. Please try again.</div>';
exit();
}
if(trim($verify) == '') {
echo '<div class="error_message">Attention! Please Verify CAPTCHA.</div>';
exit();
}else if(trim($verify) === $_SESSION["security_number"]) {
echo '<div class="error_message">Attention! The verification number you entered is incorrect.</div>';
exit();
}
if(get_magic_quotes_gpc()) {
$comments = stripslashes($comments);
}
$address = "contact#sreejesh.in";
$e_subject = 'Form Submission.';
$e_body = "You have a new Form Submission." . PHP_EOL . PHP_EOL;
$e_content = "Name: $name,\rPhone: $phone,\rEmail: $email" . PHP_EOL . PHP_EOL;
$e_reply = "";
$msg = wordwrap( $e_body . $e_content . $e_reply, 70 );
$headers = "From: $email" . PHP_EOL;
$headers .= "Reply-To: $email" . PHP_EOL;
$headers .= "MIME-Version: 1.0" . PHP_EOL;
$headers .= "Content-type: text/plain; charset=utf-8" . PHP_EOL;
$headers .= "Content-Transfer-Encoding: quoted-printable" . PHP_EOL;
if(mail($address, $e_subject, $msg, $headers)) {
// Email has sent successfully, echo a success page.
echo "<fieldset>";
echo "<div id='success_page'>";
echo "<h4>Email Sent Successfully.</h4>";
echo "<p>Thank you <strong>$name</strong>, for your interest We will contact you shortly.</p>";
echo "</div>";
echo "</fieldset>";
} else {
echo 'ERROR!';
}
For some reason I'm NOT getting value of $captcha
It returns an error says**
Currently the form get submitted without validation.
For Captcha image I use this code -
Captcha Code(IMAGE.PHP)
<?php
session_start();
$img=imagecreatefromjpeg("texture.jpg");
$security_number = empty($_SESSION['security_number']) ? 'error' : $_SESSION['security_number'];
$image_text=$security_number;
$red=rand(100,255);
$green=rand(100,255);
$blue=rand(100,255);
$text_color=imagecolorallocate($img,255-$red,255-$green,255-$blue);
$text=imagettftext($img,16,rand(-10,10),rand(10,30),rand(25,35),$text_color,"fonts/courbd.ttf",$image_text);
header("Content-type:image/jpeg");
header("Content-Disposition:inline ; filename=secure.jpg");
imagejpeg($img);
?>
I'm a beginer in PHP & I'm sitting with this code for the last few hours. PLs help.
Here is a live URL - http://aisther.com/projects/sri/
Do not echo your session variable is it being created by your image.php script and exposing it to the user makes the captcha pointless.
HTML
<form action="contact.php" method="post">
<div id="captcha">
<img src="php/image.php" alt="well, this is out capcha image" class="captcha" />
<input type="text" name="verify" id="verify" class="form-control" placeholder="Enter Captcha" />
</div>
</form>
PHP
session_start();
if($_POST'verify'] == $_SESSION["security_number"]) {
echo 'captcha matched';
} else {
echo 'bad captcha';
}
If you want to use $_POST to read the form data, the form tag needs to look like
<form action='contact.php' method='post'>
Issue solved after adding session_start(); in contact.php
final code(contact.php)
<?php
session_start();
*********************************************************
$verify = $_POST['verify'];
$captcha = $_SESSION["security_number"];
*********************************************************
if(trim($verify) == '') {
echo '<div class="error_message">Attention! Please Verify CAPTCHA.</div>';
exit();
}else if(trim($verify) != trim($captcha)) {
echo '<div class="error_message">Attention! The verification number you entered is incorrect.</div>';
exit();
}
*********************************************************
?>

Undefined variable even after using isset

I'm getting the following error for a contact form
Notice: Undefined variable: sumNums in C:\xampp\htdocs\tedx\contact.php on line 45
I've already tried 'isseting' it.
Below is my HTML markup regarding this.
<form class="contact-form" method="post" action="contact.php" name="contactform" id="contactform">
<div class="row">
<div class="large-6 columns">
<div class="row">
<div class="large-12 columns">
<label>Name<small class="astrix">*</small>
<input type="text" id="name" name="name" />
</label>
</div>
</div>
<div class="row">
<div class="large-12 columns">
<label>Email<small class="astrix">*</small>
<input type="text" id="email" name="email" />
</label>
</div>
</div>
<div class="row">
<div class="large-12 columns">
<label>Subject<small class="astrix">*</small>
<input type="text" id="subject" name="subject" />
</label>
</div>
</div>
</div>
<div class="large-6 columns">
<label>Message<small class="astrix">*</small>
<textarea cols="30" rows="8" id="comments" name="comments"></textarea>
</label>
</div>
</div>
<div class="row captcha">
<div class="large-6 columns">
<label for="captcha-code">Enter the following sum<small class="astrix">*</small><br>
<span class="captcha-chars" name="captcha-chars">
<span name="num1" id="num1">
<?php
$num1 = rand(1, 9);
echo $num1;
?>
</span>
+
<span name="num2" id="num2">
<?php
$num2 = rand(1, 9);
echo $num2;
?>
</span>
<?php $sumNums = $num1+$num2; ?>
<input type="hidden" value="<?php echo $sumNums; ?>" name="sunNums" id="sumNums">
</span>
<input type="text" id="verify" name="verify">
</label>
</div>
<div class="large-6 columns mt-25">
<button type="submit" id="submit" class="submit"><img src="img/btn-submit.png" alt=""></button>
</div>
</div>
</form>
And the PHP:
<?php
if(!$_POST) exit;
// Email address verification, do not edit.
function isEmail($email) {
return(preg_match("/^[-_.[:alnum:]]+#((([[:alnum:]]|[[:alnum:]][[:alnum:]-]*[[:alnum:]])\.)+(ad|ae|aero|af|ag|ai|al|am|an|ao|aq|ar|arpa|as|at|au|aw|az|ba|bb|bd|be|bf|bg|bh|bi|biz|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|com|coop|cr|cs|cu|cv|cx|cy|cz|de|dj|dk|dm|do|dz|ec|edu|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gh|gi|gl|gm|gn|gov|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|in|info|int|io|iq|ir|is|it|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|me|mg|mh|mil|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|museum|mv|mw|mx|my|mz|na|name|nc|ne|net|nf|ng|ni|nl|no|np|nr|nt|nu|nz|om|org|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|pro|ps|pt|pw|py|qa|re|ro|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)$|(([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5])\.){3}([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5]))$/i",$email));
}
if (!defined("PHP_EOL")) define("PHP_EOL", "\r\n");
$name = trim($_POST['name']);
$email = trim($_POST['email']);
$subject = trim($_POST['subject']);
$comments = trim(strip_tags($_POST['comments'], '<p><b><a><i>'));
$verify = trim($_POST['verify']);
if(isset($_POST['sumNums'])) {$sumNums = $_POST['sumNums'];}
if(trim($name) == '') {
echo '<div class="error_message"><i class="fi-x"></i>You must enter your name.</div>';
exit();
} else if(!ctype_alpha($name)) {
echo '<div class="error_message"><i class="fi-x"></i>Your name should\'t contain digits or speicla characters</div>';
exit();
} else if(trim($email) == '') {
echo '<div class="error_message"><i class="fi-x"></i>You must enter your email ID</div>';
exit();
} else if(!isEmail($email)) {
echo '<div class="error_message"><i class="fi-x"></i>You have entered an invalid email ID, try again.</div>';
exit();
}
if(trim($subject) == '') {
echo '<div class="error_message"><i class="fi-x"></i>You must enter a subject.</div>';
exit();
} else if(!ctype_alpha($subject)) {
echo '<div class="error_message"><i class="fi-x"></i>Your subject should\'t contain digits or speicla characters</div>';
exit();
} else if(trim($comments) == '') {
echo '<div class="error_message"><i class="fi-x"></i>You must enter a message.</div>';
exit();
} else if(!isset($verify) || trim($verify) == '') {
echo '<div class="error_message"><i class="fi-x"></i>You must enter the verification number.</div>';
exit();
} else if(trim($verify) != $sumNums) {
echo '<div class="error_message"><i class="fi-x"></i>The verification number you entered is incorrect.</div>';
exit();
}
if(get_magic_quotes_gpc()) {
$comments = stripslashes($comments);
}
// Configuration option.
// Enter the email address that you want to emails to be sent to.
// Example $address = "joe.doe#yourdomain.com";
//$address = "example#themeforest.net";
$address = "njshah#aixsol.com";
// Configuration option.
// i.e. The standard subject will appear as, "You've been contacted by John Doe."
// Example, $e_subject = '$name . ' has contacted you via Your Website.';
$e_subject = 'You\'ve been contacted by ' . $name . '.';
// Configuration option.
// You can change this if you feel that you need to.
// Developers, you may wish to add more fields to the form, in which case you must be sure to add them here.
$e_body = "You have been contacted by $name with regards to $subject, their additional message is as follows." . PHP_EOL . PHP_EOL;
$e_content = "\"$comments\"" . PHP_EOL . PHP_EOL;
$e_reply = "You can contact $name via email, $email.";
$msg = wordwrap( $e_body . $e_content . $e_reply, 70 );
$headers = "From: $email" . PHP_EOL;
$headers .= "Reply-To: $email" . PHP_EOL;
$headers .= "MIME-Version: 1.0" . PHP_EOL;
$headers .= "Content-type: text/plain; charset=utf-8" . PHP_EOL;
$headers .= "Content-Transfer-Encoding: quoted-printable" . PHP_EOL;
if(mail($address, $e_subject, $msg, $headers)) {
// Email has sent successfully, echo a success page.
echo "<div id='success_page' class='success_message'>";
echo "<p><i class='fi-check'></i>Message sent successfully.";
echo "Thank you <strong>$name</strong>, your message has been submitted to us.</p>";
echo "</div>";
} else {
echo 'ERROR!';
}
How do I solve this issue?
You need to answer yourself a question about the line below. Will the $sumNums be defined if the POST isn't submitted?
if(isset($_POST['sumNums'])) {$sumNums = $_POST['sumNums'];}
In form you gave wrong name for sunNums it should be sumNums
So, Replace
<input type="hidden" value="<?php echo $sumNums; ?>" name="sunNums" id="sumNums">
with
<input type="hidden" value="<?php echo $sumNums; ?>" name="sumNums" id="sumNums">
I have just changed the name attribute.
Your input has
name="sunNums"
and you are using
if(isset($_POST['sumNums'])) {$sumNums = $_POST['sumNums'];}
in HTML name is sunNums
<input type="hidden" value="<?php echo $sumNums; ?>" name="sunNums" id="sumNums">
but in PHP you use sumNums
if(isset($_POST['sumNums'])) {$sumNums = $_POST['sumNums'];}
Problem is this:
if(isset($_POST['sumNums'])) {$sumNums = $_POST['sumNums'];}
$sumNums variable is not defined. There is no such index in $_POST.
You can initialize the value
$sumNums = '';
before
if(isset($_POST['sumNums'])) {$sumNums = $_POST['sumNums'];}
Otherwise, you can also replace
} else if(trim($verify) != $sumNums) {
by
} else if(isset($sumNums) && trim($verify) != $sumNums) {
I hope it will help you :)
REPLACE:
<input type="hidden" value="<?php echo $sumNums; ?>" name="sunNums" id="sumNums">
TO
<input type="hidden" value="<?php echo $sumNums; ?>" name="sumNums" id="sumNums">

Contact form with required fields will not submit - using PHP validation [closed]

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.");
}

Categories