Undefined variable even after using isset - php

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">

Related

PHP - Email form is sending over 50 mails after form submit

I have a problem that after I fill out the contact form on my HTML website I receive over 50 same E-mails. Its a HTML form connected to contact.php file which code is shown bellow. I have set everything but maybe there is a problem in my code or somewhere else.
My code is over here
<?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 = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$subject = $_POST['subject'];
$comments = $_POST['comments'];
$verify = $_POST['verify'];
if(trim($name) == '') {
echo '<div class="error_message">Vyplnte meno.</div>';
exit();
} else if(trim($email) == '') {
echo '<div class="error_message">Vyplnte email.</div>';
exit();
} else if(!isEmail($email)) {
echo '<div class="error_message">Zadali ste nesprávny e-mail, skúste to znovu.</div>';
exit();
}
if(trim($comments) == '') {
echo '<div class="error_message">Vyplnte text správy.</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 = "noreply#marcelaskolenia.sk";
$address = "lubosmasura#gmail.com";
$toCustomer = $email;
// 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 = 'Mate novu spravu od ' . $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 = "Mate novu spravu od $name." . PHP_EOL . PHP_EOL;
$e_content = "\"$subject\"" . "\"$comments\"" . PHP_EOL . PHP_EOL;
$e_reply = "Kontaktujte $name cez email, $email alebo cez mobil $phone";
$msg = wordwrap( $e_body . $e_content . $e_reply, 70 );
$headers .= 'To: Test <noreply#marcelaskolenia.sk>' . "\r\n";
$headers .= 'From: Testk <noreply#marcelaskolenia.sk>' . "\r\n";
$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 "<h3 class'mark'>Sprava bola odoslana.</h3>";
echo "<p>Dakujeme <strong>$name</strong>, Vasa sprava nam bude dorucena.</p>";
echo "</div>";
echo "</fieldset>";
} else {
echo 'ERROR!';
}
HTML code
<div class="contact_form">
<div id="message"></div>
<form id="contactform" class="row" action="contact.php" name="contactform" method="post">
<div class="col-md-12">
<input type="text" name="name" id="name" class="form-control" placeholder="Meno">
<input type="text" name="email" id="email" class="form-control" placeholder="Email">
<input type="text" name="phone" id="phone" class="form-control" placeholder="Telefónne číslo">
<input type="text" name="subject" id="subject" class="form-control" placeholder="Predmet">
<textarea class="form-control" name="comments" id="comments" rows="6" placeholder="Text správy"></textarea>
<button type="submit" value="SEND" id="submit" class="btn btn-primary"> ODOSLAŤ</button>
</div>
</form>
</div>
</div><!-- end col -->
Any Ideas why is this happening?
Thank you.

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

PHP - Mail script (Select element)

I have been working on a website recently from a website template (Puremedia). The template originally had a working contact form. It consisted of "First name", "last name", "Email" and "Subject". And then of course the message. I have now replaced the "Last name" text-box with a dropdown menu. I have done so by using the html select tags. Now my question is how I would change the php scripting so that instead of sending the message (Contact form) to One predefined email. It can send it to two different email adresses. How I would like it to be implemented would be using the dropdown menu. So for example the dropdown menu would be someling along these lines: "Choose Receiver" , "Mail 1" , "Mail 2".
And then also adding a checkbox below the message field that will send a copy to the persons own email address. - Here is my contact form code:
<form name="contactForm" id="contactForm" method="post" action="">
<fieldset>
<div class="row">
<div class="six columns mob-whole">
<label for="contactFname">First Name <span class="required">*</span></label>
<input name="contactFname" type="text" id="contactFname" placeholder="First Name" value="" />
</div>
<div class="six columns mob-whole">
<select name="mailacc">
<option value="1">Send til (Vælg venligst)</option>
<option value="2">Direktør</option>
<option value="3">Bogholder</option>
</select>
</div>
</div>
<div class="row">
<div class="six columns mob-whole">
<label for="contactEmail">Email <span class="required">*</span></label>
<input name="contactEmail" type="text" id="contactEmail" placeholder="Email" value="" />
</div>
<div class="six columns mob-whole">
<label for="contactSubject">Subject</label>
<input name="contactSubject" type="text" id="contactSubject" placeholder="Subject" value="" />
</div>
</div>
<div class="row">
<div class="twelve columns">
<label for="contactMessage">Message <span class="required">*</span></label>
<textarea name="contactMessage" id="contactMessage" placeholder="Your Message" rows="10" cols="50" ></textarea>
</div>
</div>
<div>
<button class="submit full-width">Send Message</button>
<div id="image-loader">
<img src="images/loader.gif" alt="" />
</div>
</div>
</fieldset>
</form> <!-- /contactForm -->
<!-- message box -->
<div id="message-warning"></div>
<div id="message-success">
<i class="fa fa-check"></i>Your message was sent, thank you!<br />
</div>
</div> <!-- /contact-form -->
The PHP part:
<?php
// Replace this with your own email address
$siteOwnersEmail = 'mail#domain.com';
if($_POST) {
$fname = trim(stripslashes($_POST['contactFname']));
$lname = trim(stripslashes($_POST['contactLname']));
$email = trim(stripslashes($_POST['contactEmail']));
$subject = trim(stripslashes($_POST['contactSubject']));
$contact_message = trim(stripslashes($_POST['contactMessage']));
// Check First Name
if (strlen($fname) < 2) {
$error['fname'] = "Please enter your first name.";
}
// Check Last Name
if (strlen($lname) < 2) {
$error['lname'] = "Please enter your last name.";
}
// Check Email
if (!preg_match('/^[a-z0-9&\'\.\-_\+]+#[a-z0-9\-]+\.([a-z0-9\-]+\.)*+[a-z]{2}/is', $email)) {
$error['email'] = "Please enter a valid email address.";
}
// Check Message
if (strlen($contact_message) < 15) {
$error['message'] = "Please enter your message. It should have at least 15 characters.";
}
// Subject
if ($subject == '') { $subject = "Contact Form Submission"; }
// Set Name
$name = $fname . " " . $lname;
// Set Message
$message .= "Email from: " . $name . "<br />";
$message .= "Email address: " . $email . "<br />";
$message .= "Message: <br />";
$message .= $contact_message;
$message .= "<br /> ----- <br /> This email was sent from your site's contact form. <br />";
// Set From: header
$from = $name . " <" . $email . ">";
// Email Headers
$headers = "From: " . $from . "\r\n";
$headers .= "Reply-To: ". $email . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
if (!$error) {
ini_set("sendmail_from", $siteOwnersEmail); // for windows server
$mail = mail($siteOwnersEmail, $subject, $message, $headers);
if ($mail) { echo "OK"; }
else { echo "Something went wrong. Please try again."; }
} # end if - no validation error
else {
$response = (isset($error['fname'])) ? $error['fname'] . "<br /> \n" : null;
$response .= (isset($error['lname'])) ? $error['lname'] . "<br /> \n" : null;
$response .= (isset($error['email'])) ? $error['email'] . "<br /> \n" : null;
$response .= (isset($error['message'])) ? $error['message'] . "<br />" : null;
echo $response;
} # end if - there was a validation error
}
?>

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();
}
*********************************************************
?>

Issues with php verification script

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

Categories