I'm new to php and have been trying to figure out how to properly validate email addresses and that data has been entered into the text boxes. I can't really find what I need and trying to follow the examples on php.net sends me into a circle. Any help would be greatly appreciated! Also, am I even heading in the right direction with this form? The form works, I get an email formatted the way I want to either of the email address in the dropdown box.
-UPDATE- I rewrote some of my script...can someone check it out, I'm having more problems now. It will send an email even if nothing is entered into the form and even if you do it will send whatever you put. Example "email" test#example is being allowed through.
<?php
//Sainitize function
function sanitizeString($value){
$value = strip_tags($value);
$value = trim($value);
$value = escapeshellcmd($value);
$value = htmlentities($value);
return $value;
}
$send = $_POST[send];
//Email validation - does not work by the way
if (filter_var($from, FILTER_VALIDATE_EMAIL)) {
$email_error = true;
$error_message[] = "Please use a valid email format: name#domain.com";
}
if($send == 1){$email_sent = true; $step_1 = "complete";}
else{$email_sent = false; $step_1 = "complete";}
if($email_sent === true) {
$from = sanitizeString($_POST['from']);
$to = sanitizeString($_POST['to']);
$name = sanitizeString($_POST['name']);
$title = sanitizeString($_POST['title']);
$company = sanitizeString($_POST['company']);
$phone = sanitizeString($_POST['phone']);
$subject = sanitizeString($_POST['subject']);
$message = sanitizeString($_POST['message']);
// define variables and initialize with empty values
$nameErr = $addressErr = $emailErr = $messageErr = $phoneErr = "";
$name = $address = $email = $message = $phone = "";
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["phone"])) {
$phoneErr = "Please enter a phone number.";
}
else {
$phone = $_POST["phone"];
}
if (empty($_POST["message"])) {
$messageErr = "Cannot leave message box blank.";
}
else {
$message = $_POST["message"];
}
}
//select the correct to address
switch ($to) {
case "1":
$to = "contact1#example.com";
break;
case "2":
$to = "contact2#example.com";
break;
default:
$to = "contact1#example.com";
break;}
if($message_error !== true && $email_error !== true){
$email_headers = "From:".$from."\nMIME-Version: 1.0 \nContent-type: text/html; charset=iso-8859-1";
$message_send = "<h3>".$name."<br>".$title."<br>".$company."<br>".$phone."<br>".$from."</h3><hr><h4>".$subject."</h4>".$message;
if (mail($to, $subject, $message_send, $email_headers)) {$error_message = "Thank you, your email is on the way!";}
else {$error_message = "There seems to be a problem!";}}
}
?>
<body>
<form action="<?php ($_SERVER["PHP_SELF"]);?>" method="post">
<table style="border-collapse:collapse; border-spacing:0" >
<tr>
<td>Name:</td>
<td><input name="name" placeholder="Name*" type="text" class="text"/>
<span class="error"><?php echo $nameErr;?></span></td>
</tr>
<tr>
<td>Title:</td>
<td><input type="text" placeholder="Title" name="title" size="50"/></td>
</tr>
<tr>
<td>Company:</td>
<td><input type="text" placeholder="Company" name="company" size="50" /></td>
</tr>
<tr>
<td>Phone:</td>
<td>
<input name="phone" placeholder="Phone*" type="tel" size="10" maxlength="10" value="<?php echo htmlspecialchars($phone);?>"/>
<span class="style1">Example: 1234567890</span> <span class="error" style="color:#990000"><?php echo $phoneErr;?></span></td>
</tr>
<tr>
<td>Email:</td>
<td><input name="from" placeholder="Email*" type="email" class="text" value="<?php echo htmlspecialchars($email);?>">
<span class="error"><?php echo $emailErr;?></span></td>
</tr>
<tr>
<td>To:</td>
<td><select name="to" size="1">
<option value="1">Contact 1</option>
<option value="2">Contact 2</option>
</select></td>
</tr>
<tr>
<td>Subject:</td>
<td><input type="text" name="subject" placeholder="Subject" size="50" /></td>
</tr>
<tr>
<td valign="top">Detail:</td>
<td colspan="2"><textarea cols="50" rows="4" name="message" placeholder="Type your message here."></textarea></td>
</tr>
<tr>
<td colspan="2" style="text-align:center;"><input type="hidden" name="send" value="1" /><input type="submit" value="Send" name="email_1" /></td>
</tr>
</table >
</form>
For e-mail validation you can use filter_var function with FILTER_VALIDATE_EMAIL filter property. Here is nice article about input validation. Try this from php manual:
var_dump(filter_var('bob#example.com', FILTER_VALIDATE_EMAIL));
You can simplify your code, it's a bit messy. switch e-mail addresses is not very good practice. You can add values to form like this:
<select name="to" size="1">
<option value="contact1#example.com">Contact1</option>
<option value="contact2#example.com">Contact2</option>
</select>
You are also using deprecated function mysql_escape_string. ltrim and rtrim can be replaced with trim function.
UPDATE
There is still lot of mistakes in your code. Do you have displayed error reportings? Email switching is definitely not good solution for your problem. Take a look on the refactored code, it should work for you:
<?php
//Sainitize function
function sanitizeString($value)
{
$value = strip_tags($value);
$value = trim($value);
$value = escapeshellcmd($value);
$value = htmlentities($value);
return $value;
}
$errorMessage = array();
$receivers = array(
1 => 'contact1#example.com',
2 => 'contact2#example.com'
);
if(isset($_POST['form']))
{
$formData = $_POST['form'];
if (filter_var($formData['from'], FILTER_VALIDATE_EMAIL)) {
$from = sanitizeString($formData['from']);
}
else
{
$errorMessage[] = "Please use a valid email format: name#domain.com";
}
if(array_key_exists($formData['to'], $receivers))
{
$to = $receivers[$formData['to']];
}
else
{
$to = 'default#example.com';
}
if(strlen($formData['name']) > 0)
{
$name = sanitizeString($formData['name']);
}
else
{
$errorMessage[] = "Please enter your name.";
}
if(strlen($formData['title']) > 0)
{
$title = sanitizeString($formData['title']);
}
else
{
$title = '';
}
if(strlen($formData['company']) > 0)
{
$company = sanitizeString($formData['company']);
}
else
{
$company = '';
}
if(strlen($formData['phone']) > 0)
{
$phone = sanitizeString($formData['phone']);
}
else
{
$errorMessage[] = "Please enter a phone number.";
}
if(strlen($formData['subject']) > 0)
{
$subject = sanitizeString($formData['subject']);
}
else
{
$subject = '';
}
if(strlen($formData['message']) > 0)
{
$message = sanitizeString($formData['message']);
}
else
{
$errorMessage[] = 'Cannot leave message box blank.';
}
if (empty($errorMessage) && $formData['spam'] == 9)
{
$email_headers = "From:" . $from . "\nMIME-Version: 1.0 \nContent-type: text/html; charset=iso-8859-1";
$message_send = "<h3>" . $name . "<br>" . $title . "<br>" . $company . "<br>" . $phone . "<br>" . $from . "</h3><hr><h4>" . $subject . "</h4>" . $message;
if (mail($to, $subject, $message_send, $email_headers))
{
$errorMessage[] = 'Thank you, your email is on the way!';
}
else
{
$errorMessage[] = 'There seems to be a problem!';
}
}
}
?>
<body>
<?php if(!empty($errorMessage)): ?>
<div style="border: 2px solid red">
<ul>
<?php foreach ($errorMessage as $error): ?>
<li><?php echo $error; ?></li>
<?php endforeach; ?>
</ul>
</div>
<?php endif; ?>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<table style="border-collapse:collapse; border-spacing:0">
<tr>
<td>Name:</td>
<td>
<input name="form[name]" placeholder="Name*" type="text" class="text" value="<?php echo isset($name) ? $name : ''; ?>"/>
</td>
</tr>
<tr>
<td>Title:</td>
<td>
<input type="text" placeholder="Title" name="form[title]" size="50" value="<?php echo isset($title) ? $title : ''; ?>"/>
</td>
</tr>
<tr>
<td>Company:</td>
<td>
<input type="text" placeholder="Company" name="form[company]" size="50" value="<?php echo isset($company) ? $company : ''; ?>"/>
</td>
</tr>
<tr>
<td>Phone:</td>
<td>
<input name="form[phone]" placeholder="Phone*" type="tel" size="10" maxlength="10" value="<?php echo isset($phone) ? $phone : ''; ?>"/>
<span class="style1">Example: 1234567890</span>
</td>
</tr>
<tr>
<td>Email:</td>
<td>
<input name="form[from]" placeholder="Email*" type="email" class="text" value="<?php echo isset($from) ? $from : ''; ?>">
</td>
</tr>
<tr>
<td>To:</td>
<td>
<select name="form[to]" size="1">
<option value="1">Contact 1</option>
<option value="2">Contact 2</option>
</select>
</td>
</tr>
<tr>
<td>Subject:</td>
<td>
<input type="text" name="form[subject]" placeholder="Subject" size="50" value="<?php echo isset($subject) ? $subject : ''; ?>"/>
</td>
</tr>
<tr>
<td valign="top">Detail:</td>
<td colspan="2">
<textarea cols="50" rows="4" name="form[message]" placeholder="Type your message here."><?php echo isset($message) ? $message : ''; ?></textarea>
</td>
</tr>
<tr>
<td></td>
<td>
3x3 = <input type="text" value="" name="form[spam]"/>
<input type="submit" value="Send" />
</td>
</tr>
</table>
</form>
I found this on php.net.. Does it work?
if (filter_var($from, FILTER_VALIDATE_EMAIL)) {
$email_error = true;
$error_message[] = "Please use a valid email format: name#domain.com";
}
The Filter var does work. Try the following piece of code.
<?php
$emailError = array();
if(isset($_POST["send"])){
$from = $_POST["from"];
if (!filter_var($from, FILTER_VALIDATE_EMAIL)) {
$emailError[] = "Please use a valid email format: name#domain.com\n\r";
}
else {
echo $from . " is a valid email.\n\r";
}
if ($emailError){
foreach ($emailError as $key){
echo $key;
}
}
} else {
?>
<form action="<?php ($_SERVER["PHP_SELF"]);?>" method="post">
<table>
<tr>
<td>Email:</td>
<td>
<input name="from" placeholder="Email*" type="email" class="text" value="">
</td>
</tr>
</table>
<input type="submit" value="Send" name="send" />
</form>
<?php
}
?>
Related
i am trying to create simple contact form with captcha in php. However it turns out implementing captcha is out of my league.
I found a simple answer on stackoverflow opn similar problem which pushed me 1 step closer to the end, but again i got stuck.
So i need a contact form that only check if text is entered and if correct captcha is answered, email is not mandatory.
</br>
<?php
$a=rand(2,9);
$b=rand(2,9);
$c=$a+$b;
if (isset($_POST['contact_text']) && isset($_POST['contact_email']) ) {
$contact_text = $_POST['contact_text'];
$contact_email = $_POST['contact_email'];
$recaptcha = $_POST['recaptcha'];
$info = 'Pranešimas apie korupciją: ';
$sender = 'Atsiuntė: ';
if (!empty($contact_text) && ($recaptcha == $c )) {
echo $recaptcha;
$to = 'muksinovas#gmail.com';
$subject = 'Korupcija';
$body = $sender."\n".$contact_email."\n".$info."\n".$contact_text;
$headers = 'From: '.$contact_email;
if (#mail($to,$subject, $body, $headers)) {
echo 'Jūsų pranešimas sėkmingai išsiustas. ';
} else {
} echo 'Įvyko klaida, bandykite dar karta.';
} else {
echo 'Neteisingai užpildyta forma.';
}
}
?>
<form action="contact1.php" method="post">
Pranešimas apie korupciją:<br><textarea name="contact_text" rows="6" cols="30" maxlength="1000" ></textarea><br><br> <!-- -->
Email (nebūtinas):<br><input type="text" name="contact_email" maxlength="30">
<?php echo $a."+".$b."="?><input type="number" name="recaptcha" maxlength="2" style="width:40px" />
<input type="submit" value="Siusti">
<br>
</form>
Now the problem is that I always get the message that details are incorrect. I tried to echo recaptcha just to see if $c is correct and it works. But for some reason not able to compare $recaptcha with $c or some other issue I am not sure.
The value of $c will be a completely different value when the user submits the contact form vs when your validation checks it. The value will change on every request because the script is re-interpreted.
You will have to save the value of $c on the initial page load, so that you can compare it afterwards in the next request. You can do that by storing it in $_SESSION.
You can write this
<?php
$min_number = 2;
$max_number = 9;
$random_number1 = mt_rand($min_number, $max_number);
$random_number2 = mt_rand($min_number, $max_number);
if (isset($_POST['contact_text']) && isset($_POST['contact_email']) ) {
$contact_text = $_POST['contact_text'];
$contact_email = $_POST['contact_email'];
$recaptcha = $_POST['recaptcha'];
$firstNumber = $_POST["firstNumber"];
$secondNumber = $_POST["secondNumber"];
$checkTotal = $firstNumber + $secondNumber;
$info = 'Pranešimas apie korupciją: ';
$sender = 'Atsiuntė: ';
if (!empty($contact_text) && ($recaptcha != $checkTotal )) {
echo $recaptcha;
$to = 'muksinovas#gmail.com';
$subject = 'Korupcija';
$body = $sender."\n".$contact_email."\n".$info."\n".$contact_text;
$headers = 'From: '.$contact_email;
if (#mail($to,$subject, $body, $headers)) {
echo 'Jūsų pranešimas sėkmingai išsiustas. ';
} else {
} echo 'Įvyko klaida, bandykite dar karta.';
} else {
echo 'Neteisingai užpildyta forma.';
}
}
?>
<form action="contact1.php" method="post">
Pranešimas apie korupciją:<br><textarea name="contact_text" rows="6" cols="30" maxlength="1000" ></textarea><br><br> <!-- -->
Email (nebūtinas):<br><input type="text" name="contact_email" maxlength="30">
<?php
echo $random_number1 . ' + ' . $random_number2 . ' = ';
?>
<input type="number" name="recaptcha" maxlength="2" style="width:40px" />
<input name="firstNumber" type="hidden" value="<?php echo $random_number1; ?>" />
<input name="secondNumber" type="hidden" value="<?php echo $random_number2; ?>" />
<input type="submit" value="Siusti">
<br>
</form>
This might solve your problem
you should to use session to solve your problem, i did little changes in your code, it should to work perfectly.
<?php
#session_start();
if (isset($_POST['contact_text']) && isset($_POST['contact_email']) ) {
$contact_text = $_POST['contact_text'];
$contact_email = $_POST['contact_email'];
$recaptcha = $_POST['recaptcha'];
$info = 'Pranešimas apie korupciją: ';
$sender = 'Atsiuntė: ';
if (!empty($contact_text) && ($recaptcha == $_SESSION["captcha"])) {
echo $recaptcha;
$to = 'muksinovas#gmail.com';
$subject = 'Korupcija';
$body = $sender."\n".$contact_email."\n".$info."\n".$contact_text;
$headers = 'From: '.$contact_email;
if (#mail($to,$subject, $body, $headers)) {
echo 'Jūsų pranešimas sėkmingai išsiustas. ';
} else {
} echo 'Įvyko klaida, bandykite dar karta.';
}else{
echo 'Neteisingai užpildyta forma.';
}
}else{
$a=rand(2,9);
$b=rand(2,9);
$c=$a+$b;
//setting captcha code in session
$_SESSION["captcha"] = $c;
?>
<form action="contact1.php" method="post">
Pranešimas apie korupciją:<br><textarea name="contact_text" rows="6" cols="30" maxlength="1000" ></textarea><br><br> <!-- -->
Email (nebūtinas):<br><input type="text" name="contact_email" maxlength="30">
<?php echo $a."+".$b."="?><input type="number" name="recaptcha" maxlength="2" style="width:40px" />
<input type="submit" value="Siusti">
<br>
</form>
<?php
}
?>
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
this is my form as it sents the email to the four different email on selectoin of different radio buttons.....But i donot want the form to be submitted until the captcha is verified..so i added this captcha but it is not working I dont know why.Please help me on this... .Thanks in advance.
<?php
session_start();
//error_reporting(E_ERROR | E_PARSE);
//echo "<pre>";
//print_r($_REQUEST);
if(!empty($_POST['answer']) )
{
//echo "You entered " . htmlentities($_POST['answer']) . " which is ";
if ($_SESSION['answer'] == $_POST['answer'])
{
//echo 'correct';
$validatedCaptcha = true;
}
else
{
echo '<center>'.'You Filled wrong Captcha. We expected ' . $_SESSION['answer'].' .Kindly Fill the Form Again'.'</center>';
$validatedCaptcha = false;
}
}
$digit1 = mt_rand(1, 20);
$digit2 = mt_rand(1, 20);
if (mt_rand(0, 1) === 1) {
$math = "$digit1 + $digit2";
$_SESSION['answer'] = $digit1 + $digit2;
} else {
if($digit1 >= $digit2)
{
$math = "$digit1 - $digit2";
$_SESSION['answer'] = $digit1 - $digit2;
}
else if($digit1 < $digit2)
{
$math = "$digit2 - $digit1";
$_SESSION['answer'] = $digit2 - $digit1;
}
}
//echo "<pre>";
//print_r($_SESSION);
?>
<center>
<?php
$name = $_REQUEST['name11'];
$email = $_REQUEST['email11'];
$phone12 = $_REQUEST['mobile11'];
$subject = $_REQUEST['subject11'];
$message1 = $_REQUEST['message11'];
$zone1 = $_REQUEST['zone1'];
$null_virdi = "-f " . $email;
if (isset($_REQUEST['submit']) && $validatedCaptcha == true ) {
$message = "Name: " . $name . "\n" . "Email: " . $email . "\n" . "phone :" . $phone12 . "\n" . "Message :" . $message1;
if ($_REQUEST['zone1'] == "South") {
echo "Thank you for Contacting our South Indian Zonal Office";
mail("abc#gmail.com", $subject, $message, null, $null_virdi);
}
if ($_REQUEST['zone1'] == "Delhi") {
mail("abc#gmail.com", $subject, $message, null, $null_virdi);
echo "Thank you for Contacting our Delhi Office";
}
if ($_REQUEST['zone1'] == "Hyderabad") {
mail("abc3#gmail.com", $subject, $message, null, $null_virdi);
echo "Thank you for Contacting our Hyderabad & AP Office";
}
if ($_REQUEST['zone1'] == "Pune") {
mail("abc4#gmail.com", $subject, $message, null, $null_virdi);
echo "Thank you for Contacting our Pune/Nasik Office";
}
if ($_REQUEST['zone1'] == "west") {
mail("abc5#gmail.com", $subject, $message, null, $null_virdi);
echo "Thank you for Contacting our West Zone Office";
}
}
?>
<html><head>
<script>
function validateForm()
{
var x = document.forms["myForm"]["email1"].value;
var atpos = x.indexOf("#");
var dotpos = x.lastIndexOf(".");
if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= x.length)
{
alert("Not a valid e-mail address");
return false;
}
}
</script>
</head><body>
<div style="width:50%;border: 4px double #dbd395;margin: 0;padding: 28px 0px 0px 34px;background-color: #F8F8F8">
<form name="myForm" action="" onSubmit="return validateForm();" method="post" >
<table >
<tr>
<h3 style="margin-left:5px;">Enquiry for Quotation</h3>
</tr>
<tr>
<td></td>
</tr>
<tr>
<td>Name <font color="#FF0000">*</font> : <input type="text" required="required" name="name11" size="40"/></td>
</tr>
<td></td>
</tr>
<tr>
<td>Email <font color="#FF0000">*</font> : <input type="text" required="required" name="email11" size="40"/></td>
</tr>
<tr>
<td></td>
</tr>
<tr>
<td>Mobile <font color="#FF0000">*</font> : <input type="text" required="required" name="mobile11" size="40"/></td>
</tr>
<tr>
<td>Zone <font color="#FF0000">*</font> : <input type="radio" required="required" name="zone1" value="South"/>South India <input type="radio" name="zone1" value="Delhi" />Delhi NCR <input type="radio" name="zone1" value="Hyderabad"/>Hyderabad & AP <br> <input type="radio" name="zone1" value="Pune"/>Pune/Nashik <input type="radio" name="zone1" value="west"/>Other </td>
</tr>
<td></td>
</tr>
<tr>
<td>Subject <font color="#FF0000">*</font> : <input type="text" required="required" name="subject11" size="40"/></td>
</tr>
<tr>
<td></td>
</tr>
<tr>
<td style="vertical-align: top;"><font style=vertical-align:top; color="#000000">Message</font><font style=vertical-align:top; color="#FF0000">* :</font> <textarea rows="4" cols="32" name="message11" required="required"/></textarea></td>
</tr>
<tr><td><center><b>Captcha</b></center></td></tr>
<tr><td align="center">What's <?php echo $math; ?> = <input size="5" name="answer" type="text" /><br /></td></tr>
<tr>
<td align="center">
<input type="submit" name="submit" value="Send Message"/></td>
</tr>
</table>
</form>
</div>
<body/>
</html>
</center>
Simply create an $error variable that is set to false. If the captcha is wrong, then set it to true.
Only process the form if $error == false
If you wanted to validate the captcha (not sure why) before the form is submitted, you would need to use ajax that calls the php script that verify's it.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
this is my form as it sents the email to the four different email on selectoin of different radio buttons.....But i donot want the form to be submitted until the captcha is verified..so i added this captcha but it is not working I dont know why.Please help me on this... .Thanks in advance.
<?php
session_start();
//error_reporting(E_ERROR | E_PARSE);
//echo "<pre>";
//print_r($_REQUEST);
if(!empty($_POST['answer']) )
{
//echo "You entered " . htmlentities($_POST['answer']) . " which is ";
if ($_SESSION['answer'] == $_POST['answer'])
{
//echo 'correct';
$validatedCaptcha = true;
}
else
{
echo '<center>'.'You Filled wrong Captcha. We expected ' . $_SESSION['answer'].' .Kindly Fill the Form Again'.'</center>';
$validatedCaptcha = false;
}
}
$digit1 = mt_rand(1, 20);
$digit2 = mt_rand(1, 20);
if (mt_rand(0, 1) === 1) {
$math = "$digit1 + $digit2";
$_SESSION['answer'] = $digit1 + $digit2;
} else {
if($digit1 >= $digit2)
{
$math = "$digit1 - $digit2";
$_SESSION['answer'] = $digit1 - $digit2;
}
else if($digit1 < $digit2)
{
$math = "$digit2 - $digit1";
$_SESSION['answer'] = $digit2 - $digit1;
}
}
//echo "<pre>";
//print_r($_SESSION);
?>
<center>
<?php
$name = $_REQUEST['name11'];
$email = $_REQUEST['email11'];
$phone12 = $_REQUEST['mobile11'];
$subject = $_REQUEST['subject11'];
$message1 = $_REQUEST['message11'];
$zone1 = $_REQUEST['zone1'];
$null_virdi = "-f " . $email;
if (isset($_REQUEST['submit']) && $validatedCaptcha == true ) {
$message = "Name: " . $name . "\n" . "Email: " . $email . "\n" . "phone :" . $phone12 . "\n" . "Message :" . $message1;
if ($_REQUEST['zone1'] == "South") {
echo "Thank you for Contacting our South Indian Zonal Office";
mail("abc#gmail.com", $subject, $message, null, $null_virdi);
}
if ($_REQUEST['zone1'] == "Delhi") {
mail("abc#gmail.com", $subject, $message, null, $null_virdi);
echo "Thank you for Contacting our Delhi Office";
}
if ($_REQUEST['zone1'] == "Hyderabad") {
mail("abc3#gmail.com", $subject, $message, null, $null_virdi);
echo "Thank you for Contacting our Hyderabad & AP Office";
}
if ($_REQUEST['zone1'] == "Pune") {
mail("abc4#gmail.com", $subject, $message, null, $null_virdi);
echo "Thank you for Contacting our Pune/Nasik Office";
}
if ($_REQUEST['zone1'] == "west") {
mail("abc5#gmail.com", $subject, $message, null, $null_virdi);
echo "Thank you for Contacting our West Zone Office";
}
}
?>
<html><head>
<script>
function validateForm()
{
var x = document.forms["myForm"]["email1"].value;
var atpos = x.indexOf("#");
var dotpos = x.lastIndexOf(".");
if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= x.length)
{
alert("Not a valid e-mail address");
return false;
}
}
</script>
</head><body>
<div style="width:50%;border: 4px double #dbd395;margin: 0;padding: 28px 0px 0px 34px;background-color: #F8F8F8">
<form name="myForm" action="" onSubmit="return validateForm();" method="post" >
<table >
<tr>
<h3 style="margin-left:5px;">Enquiry for Quotation</h3>
</tr>
<tr>
<td></td>
</tr>
<tr>
<td>Name <font color="#FF0000">*</font> : <input type="text" required="required" name="name11" size="40"/></td>
</tr>
<td></td>
</tr>
<tr>
<td>Email <font color="#FF0000">*</font> : <input type="text" required="required" name="email11" size="40"/></td>
</tr>
<tr>
<td></td>
</tr>
<tr>
<td>Mobile <font color="#FF0000">*</font> : <input type="text" required="required" name="mobile11" size="40"/></td>
</tr>
<tr>
<td>Zone <font color="#FF0000">*</font> : <input type="radio" required="required" name="zone1" value="South"/>South India <input type="radio" name="zone1" value="Delhi" />Delhi NCR <input type="radio" name="zone1" value="Hyderabad"/>Hyderabad & AP <br> <input type="radio" name="zone1" value="Pune"/>Pune/Nashik <input type="radio" name="zone1" value="west"/>Other </td>
</tr>
<td></td>
</tr>
<tr>
<td>Subject <font color="#FF0000">*</font> : <input type="text" required="required" name="subject11" size="40"/></td>
</tr>
<tr>
<td></td>
</tr>
<tr>
<td style="vertical-align: top;"><font style=vertical-align:top; color="#000000">Message</font><font style=vertical-align:top; color="#FF0000">* :</font> <textarea rows="4" cols="32" name="message11" required="required"/></textarea></td>
</tr>
<tr><td><center><b>Captcha</b></center></td></tr>
<tr><td align="center">What's <?php echo $math; ?> = <input size="5" name="answer" type="text" /><br /></td></tr>
<tr>
<td align="center">
<input type="submit" name="submit" value="Send Message"/></td>
</tr>
</table>
</form>
</div>
<body/>
</html>
</center>
Your "captcha" is totally weak: the "answer" is a value between (1+1) and (20+20), giving a number of not more than 39 different results in a consecutive row (2...40).
As there are parsers out there (and I've seen them working on various forms with "captchas" like this) which just simply brute force post random numbers from 1...100 against forms like this, it will take them a couple of minutes to post/register/whatever to your site.
Well i didnt get the proper answer i asked for...but the problem was i was using this form in the wordpress page and it was not working as captcha validation always went wrong and form always used to echo that your captcha is wrong that is present in the else part. But after doing some research i found that problem was due to session which I was using in my form I have got to know that wordpress has its own session so validation will always come wrong. so i did this and My form is working now. Hope it will help anybody else also.
<?php //error_reporting(E_ERROR | E_PARSE); ?>
<?php
if(!empty($_POST['answer']) )
{
//echo "You entered " . htmlentities($_POST['answer']) . " which is ";
if ($_REQUEST['answer'] == $_POST['answer'])
{
//echo 'correct';
$validatedCaptcha = true;
}
else
{
echo '<center>'.'You Filled wrong Captcha. We expected ' . $_REQUEST['answer'].' .Kindly Fill the Form Again'.'</center>';
$validatedCaptcha = false;
}
}
$digit1 = mt_rand(1, 20);
$digit2 = mt_rand(1, 20);
if (mt_rand(0, 1) === 1) {
$math = "$digit1 + $digit2";
$_REQUEST['answer'] = $digit1 + $digit2;
} else {
if($digit1 >= $digit2)
{
$math = "$digit1 - $digit2";
$_REQUEST['answer'] = $digit1 - $digit2;
}
else if($digit1 < $digit2)
{
$math = "$digit2 - $digit1";
$_REQUEST['answer'] = $digit2 - $digit1;
}
}
//echo "<pre>";
//print_r($_SESSION);
?>
<center>
<?php
$name = $_REQUEST['name11'];
$email = $_REQUEST['email11'];
$phone12 = $_REQUEST['mobile11'];
$subject = $_REQUEST['subject11'];
$message1 = $_REQUEST['message11'];
$zone1 = $_REQUEST['zone1'];
$null_virdi = "-f " . $email;
if (isset($_REQUEST['submit']) && $validatedCaptcha == true ) {
$message = "Name: " . $name . "\n" . "Email: " . $email . "\n" . "phone :" . $phone12 . "\n" . "Message :" . $message1;
if ($_REQUEST['zone1'] == "South") {
echo "Thank you for Contacting our South Indian Zonal Office";
mail("blrbranch#sonatech.net", $subject, $message, null, $null_virdi);
}
if ($_REQUEST['zone1'] == "Delhi") {
mail("sales#sonatech.net", $subject, $message, null, $null_virdi);
echo "Thank you for Contacting our Delhi Office";
}
if ($_REQUEST['zone1'] == "Hyderabad") {
mail("chandel#sonatech.net", $subject, $message, null, $null_virdi);
echo "Thank you for Contacting our Hyderabad & AP Office";
}
if ($_REQUEST['zone1'] == "Pune") {
mail("manjot#hitechwebsolutions.in,pankaj#sonatech.net", $subject, $message, null, $null_virdi);
echo "Thank you for Contacting our Pune/Nasik Office";
}
if ($_REQUEST['zone1'] == "west") {
mail("sales#sonatech.net", $subject, $message, null, $null_virdi);
echo "Thank you for Contacting our West Zone Office";
}
}
?>
<html><head>
<script>
function validateForm()
{
var x = document.forms["myForm"]["email1"].value;
var atpos = x.indexOf("#");
var dotpos = x.lastIndexOf(".");
if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= x.length)
{
alert("Not a valid e-mail address");
return false;
}
}
</script>
</head><body>
<div style="width:50%;border: 4px double #dbd395;margin: 0;padding: 28px 0px 0px 34px;background-color: #F8F8F8">
<form name="myForm" action="" onSubmit="return validateForm();" method="post" >
<table >
<tr>
<h3 style="margin-left:5px;">Enquiry for Quotation</h3>
</tr>
<tr>
<td></td>
</tr>
<tr>
<td>Name <font color="#FF0000">*</font> : <input type="text" required="required" name="name11" size="40"/></td>
</tr>
<td></td>
</tr>
<tr>
<td>Email <font color="#FF0000">*</font> : <input type="text" required="required" name="email11" size="40"/></td>
</tr>
<tr>
<td></td>
</tr>
<tr>
<td>Mobile <font color="#FF0000">*</font> : <input type="text" required="required" name="mobile11" size="40"/></td>
</tr>
<tr>
<td>Zone <font color="#FF0000">*</font> : <input type="radio" required="required" name="zone1" value="South"/>South India <input type="radio" name="zone1" value="Delhi" />Delhi NCR <input type="radio" name="zone1" value="Hyderabad"/>Hyderabad & AP <br> <input type="radio" name="zone1" value="Pune"/>Pune/Nashik <input type="radio" name="zone1" value="west"/>Other </td>
</tr>
<td></td>
</tr>
<tr>
<td>Subject <font color="#FF0000">*</font> : <input type="text" required="required" name="subject11" size="40"/></td>
</tr>
<tr>
<td></td>
</tr>
<tr>
<td style="vertical-align: top;"><font style=vertical-align:top; color="#000000">Message</font><font style=vertical-align:top; color="#FF0000">* :</font> <textarea rows="4" cols="32" name="message11" required="required"/></textarea></td>
</tr>
<tr><td><center><b>Captcha</b></center></td></tr>
<tr><td align="center">What's <?php echo $math; ?> = <input size="5" name="answer" type="text" /><br /></td></tr>
<tr>
<td align="center">
<input type="submit" name="submit" value="Send Message"/></td>
</tr>
</table>
</form>
</div>
<body/>
</html>
</center>
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 realise this question has been asked numerous times before but everyone's code is obviously different and I am quite new to php so just looking to see if someone can give me some help.
I have created a basic contact form for a site but for some reason the information is not being sent to my email address although I believe that the form is submitted?
my PHP code is:
<?php
session_start();
//$to_mail = "architects#palavin.com,t.lavin#palavin.com,12yorkcourt#gmail.com";
$to_mail = "danny#enhance.ie";
//$cc="paul#enhance.ie";
$mail_sent = 0;
if(isset($_POST['submit'])){
//echo "the form was submitted";
$error= array();
$name = trim(strip_tags($_POST['name']));
if($name == "")
$error['name'] = 1;
$email = trim(strip_tags($_POST['email']));
if($email == "")
$error['email'] = 1;
$phone = trim(strip_tags($_POST['phone']));
$address = trim(strip_tags($_POST['address']));
$description = trim(strip_tags($_POST['description']));
$str = trim(strip_tags($_POST['secu']));
if ( isset($_SESSION['code_']) && $_SESSION['code_'] == strtoupper($str)){} else {$error['secu'] = 1;}
if(empty($error)){
$headers = 'From: "Euro Insulation" <no-reply#euroinsulations.ie>'."\r\n";
//$headers .= 'CC: "'.$cc.'" <'.$cc.'>'."\r\n";
$headers .= 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=utf-8' . "";
$subject = "New contact message";
$message = "New Contact message, received from: <br /> \n ";
$message .= "<b>Name</b> ".$name."<br /> \n";
$message .= "<b>Email</b> ".$email."<br /> \n";
$message .= "<b>Phone</b> ".$phone."<br /> \n";
$message .= "<b>Address</b> ".$address."<br /> \n";
$message .= "<b>Description</b> ".$description."<br /> \n";
if(#mail($to_mail,$subject,$message,$headers ))
{
echo "mail sent";
$mail_sent = 1;
}
else echo "mail not sent";
}
}
?>
my html form looks like this:
<table width="100%" border="0" cellspacing="0" cellpadding="10">
<tr>
<td width="65%" valign="top"><p class="header"><br>
Contact US <br>
</p>
<?php if($mail_sent==1){
print "Thank you for your message.";
} else { ?>
<form class="email_sub" method="post" >
<table width="77%" border="0" align="center" cellpadding="2" cellspacing="0">
<tr>
<td><label for="name" class="formtext" <?php if($error['name']==1) echo "style='color:red;'" ?> >Name:</label></td>
<td><input type="text" name="name" id="text" <?php if($name) echo "value='".$name."'" ?> /></td>
</tr>
<tr>
<td><label for="phone" class="formtext">Number:</label></td>
<td><input type="text" name="phone" id="phone"/><tr>
<br />
<tr>
<td><label for="email" class="textarea" <?php if($error['email']==1) echo "style='color:red;'" ?>>Email:</label></td>
<td><input type="text" name="email" id="email" <?php if($email) echo "value='".$email."'" ?> /></td>
</tr>
<tr>
<td><br /></td>
</tr>
<tr><td><label for="address" class="textarea">Address/Location of project:</label></td>
<td><textarea rows="3" cols="20" name="address" id="address" style="width: 400px;"><?php if($address!="") echo $address ?></textarea></td>
</tr>
<tr>
<td><br /></td>
</tr>
<br />
<tr>
<td><label for="description" class="fixedwidth">Enquiry</label></td>
<td><textarea rows="3" cols="20" name="description" id="description" style="width: 400px;"><?php if($description!="") echo $description; ?></textarea></td>
<tr>
<td><br /></td>
</tr>
<!-- form -->
<tr>
<td><label> </label></td>
<td><input type="submit" value="Submit" name="submit" /></td>
</tr>
</table>
</form>
<?php } ?>
Am i missing something obvious here?? Any help will really be appreciated thanks!
You have used sessions which is not required here, you can also use flag variable instead of arrays in this simple form, use this updated code.
<?php
//$to_mail = "architects#palavin.com,t.lavin#palavin.com,12yorkcourt#gmail.com";
$to_mail = "danny#enhance.ie";
//$cc="paul#enhance.ie";
$mail_sent = 0;
if(isset($_POST['submit'])){
//echo "the form was submitted";
$name = trim(strip_tags($_POST['name']));
if($name == "")
$error = true;
$email = trim(strip_tags($_POST['email']));
if($email == "")
$error = true;
$phone = trim(strip_tags($_POST['phone']));
$address = trim(strip_tags($_POST['address']));
$description = trim(strip_tags($_POST['description']));
if($error != true){
$headers = 'From: "Euro Insulation" <no-reply#euroinsulations.ie>'."\r\n";
//$headers .= 'CC: "'.$cc.'" <'.$cc.'>'."\r\n";
$headers .= 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=utf-8' . "";
$subject = "New contact message";
$message = "New Contact message, received from: <br /> \n ";
$message .= "<b>Name</b> ".$name."<br /> \n";
$message .= "<b>Email</b> ".$email."<br /> \n";
$message .= "<b>Phone</b> ".$phone."<br /> \n";
$message .= "<b>Address</b> ".$address."<br /> \n";
$message .= "<b>Description</b> ".$description."<br /> \n";
if(#mail($to_mail,$subject,$message,$headers))
{
echo "mail sent";
$mail_sent = 1;
}
else echo "mail not sent";
} else {
echo 'validation error';
}
}
?>
You have also missed out the else statement for your form validation test so no errors getting displayed when you submit form.
Remove the at sign from mail function and see what errors your get. #mail suppresses errors from being displayed.
Comment out the following line: if ( isset($SESSION['code']) && $SESSION['code'] == strtoupper($str)){} else {$error['secu'] = 1;}
You should be able to reach the mail function.