PHP form send to specific email by Select option - php

The contact form I am currently working on sends to 3 email addresses. I would like to have the form send to another email address only when the Naples location option is selected. The other locations do not currently need a separate email address. I tried adding in
switch($_POST['location'])
{
case “naples″: $my_email = ‘naples#email.com’; break;
}
I thought this had worked but no email was sent out when submitted and I couldn't distinguish an error. Is it possible to allow one location option when selected to tack on another email address to the original 3 recipients? Thank you guys in advance code posted below.
<?
ob_start();
if(isset($_POST['registersubmit']))
{
unset($badcaptcha);
require_once('captcha.php');
$privatekey = "....";
$resp = recaptcha_check_answer ($privatekey,$_SERVER["REMOTE_ADDR"],$_POST["recaptcha_challenge_field"],$_POST["recaptcha_response_field"]);
if (!$resp->is_valid)
{
$badcaptcha=true;
}
else
{
//Send email
//foo#alpha.com
$to = "foo#alpha.com\r\n";
$from = "foo#alpha.com <foo#alpha.com>";
$subject = "Contact Foo\r\n";
$body = "Contact Foo\r\n\n";
$body .= "Full Name: ".$_POST['Fname']."\r\n\n";
$body .= "Business Name: ".$_POST['Bname']."\r\n\n";
$body .= "Email: ".$_POST['email']."\r\n\n";
$body .= "Address: ".$_POST['address']."\r\n\n";
$body .= "City: ".$_POST['city']."\r\n\n";
$body .= "State: ".$_POST['state']."\r\n\n";
$body .= "Zip Code: ".$_POST['zipcode']."\r\n\n";
$body .= "Phone: ".$_POST['phone']."\r\n\n";
$body .= "Location: ".$_POST['location']."\r\n\n";
$body .= "Interests: \r\n\n";
$body .= "*".$_POST['services1']."*".$_POST['services2']."*".$_POST['services3']."*".$_POST['services4']."*".$_POST['services5']."*".$_POST['services6']."*".$_POST['services7']."*".$_POST['services8']."*".$_POST['services9']."\r\n\n";
$body .= "Comments/Message: ".$_POST['details']."\r\n\n";
$headers = "MIME-Version: 1.0\r\n";
$headers .= "Content-type: text/plain; charset=iso-8859-1\r\n";
mail($to, $subject, $body, "From: ".$from."\r\n".$headers);
//Send copy beta#foo.com
$to = "beta#foo.com\r\n";
mail($to, $subject, $body, "From: ".$from."\r\n".$headers);
$to = "tom#foo.com\r\n";
mail($to, $subject, $body, "From: ".$from."\r\n".$headers);
header("Location:thankyou_contact2.php");
}
}
$linkname="contact";
if(empty($id)) { $id = 10; $showplus = "Y"; }
include("includes/header.php");
?>
<div id="main"><table width="621" cellspacing="0" cellpadding="0">
<h1>CONTACT US</h1>
<br />
Use Our Online Form (below) or Contact Your Nearest Location
<?
if(isset($badcaptcha))
{
?>
<b><font color="red">INCORRECT SECURITY CODE, PLEASE TRY AGAIN</font></b><br /> <br />
<?
}
?>
<br />
<br />
<div id="contact_form"> <!--onsubmit="return validate2()" -->
<form method="post" name="contact_form" onsubmit="return validate3()" >
<label>
<span>Full Name<font color="#FF0000">*</font></span>
<input size="31" name="Fname" value="<? if(!empty($_POST['Fname'])) { echo $_POST['Fname']; } else { echo "Full Name"; } ?>" class="input-text" maxlength="100" OnFocus="if (this.value == 'Full Name') {this.value=''}" onblur="if (this.value == '') {this.value='Full Name'}"/>
</label>
<label>
<span>Business Name<font color="#FF0000">*</font></span>
<input size="31" name="Bname" value="<? if(!empty($_POST['Bname'])) { echo $_POST['Bname']; } else { echo "Business Name"; } ?>" class="input-text" maxlength="100" OnFocus="if (this.value == 'Business Name') {this.value=''}" onblur="if (this.value == '') {this.value='Business Name'}"/>
</label>
<label>
<span>Email Address<font color="#FF0000">*</font></span>
<input size="31" name="email" value="<? if(!empty($_POST['email'])) { echo $_POST['email']; } else { echo "Email Address"; } ?>" class="input-text" maxlength="100" onfocus="if (this.value == 'Email Address') {this.value=''}" onblur="if (this.value == '') {this.value='Email Address'}" />
</label>
<label>
<span>Address</span>
<input size="31" name="address" value="<? if(!empty($_POST['address'])) { echo $_POST['address']; } else { echo "Address"; } ?>" class="input-text" maxlength="100" OnFocus="if (this.value == 'Address') {this.value=''}" onblur="if (this.value == '') {this.value='Address'}" />
</label>
<label>
<span>City</span>
<input size="31" name="city" value="<? if(!empty($_POST['city'])) { echo $_POST['city']; } else { echo "City"; } ?>" class="input-text" maxlength="100" OnFocus="if (this.value == 'City') {this.value=''}" onblur="if (this.value == '') {this.value='City'}" />
</label>
<label> <span>State</span><select name="state" id="state">
<option value="State">State</option>
<option value="AK">Alaska</option>
<option value="AL">Alabama</option>
</select> </label>
<label>
<span>Zip Code</span>
<input size="31" name="zipcode" value="<? if(!empty($_POST['zipcode'])) { echo $_POST['zipcode']; } else { echo "Zip Code"; } ?>" class="input-text" maxlength="10" OnFocus="if (this.value == 'Zip Code') {this.value=''}" onblur="if (this.value == '') {this.value='Zip Code'}" />
</label>
<label>
<span>Phone<font color="#FF0000">*</font></span>
<input size="31" name="phone" value="<? if(!empty($_POST['phone'])) { echo $_POST['phone']; } else { echo "Phone"; } ?>" class="input-text" maxlength="30" OnFocus="if (this.value == 'Phone') {this.value=''}" onblur="if (this.value == '') {this.value='Phone'}" />
</label>
<label> <span>Location<font color="#FF0000">*</font></span> <select name="location" id="location">
<option value="location">Nearest Location</option>
<option value="Naples">Naples</option>
<option value="Cherokee">Cherokee</option>
</select> </label>
<label>
<span> </span>
<strong>Interests</strong> <br />
<input type="checkbox" name="services1" value="Trucks Sales"<? if($_POST['services1']=="Trucks Sales") { echo " checked"; } ?> /> Trucks Sales
<input type="checkbox" name="services2" value="Rentals & Leasing"<? if($_POST['services2']=="Rentals & Leasing") { echo " checked"; } ?> /> Rentals & Leasing
</label>
<!-- <label>
<span> </span>
<input type="checkbox" name="services2" value="Rentals & Leasing"< ? if($_POST['services2']=="Rentals & Leasing") { echo " checked"; } ?> /> Rentals & Leasing
</label> -->
<label>
<span> </span>
<input type="checkbox" name="services3" value="Parts"<? if($_POST['services3']=="Parts") { echo " checked"; } ?> /> Parts
<input type="checkbox" name="services4" value="Service & Repair"<? if($_POST['services4']=="Service & Repair") { echo " checked"; } ?> /> Service & Repair
</label>
<!-- <label>
<span> </span>
<input type="checkbox" name="services4" value="Service & Repair"< ? if($_POST['services4']=="Service & Repair") { echo " checked"; } ?> /> Service & Repair
</label> -->
<label>
<span> </span>
<input type="checkbox" name="services5" value="Fleet Maintenance Management"<? if($_POST['services5']=="Fleet Maintenance Management") { echo " checked"; } ?> /> Fleet Maintenance Management
<input type="checkbox" name="services6" value="Other"<? if($_POST['services6']=="Other") { echo " checked"; } ?> /> Other
</label>
<!-- <label>
<span> </span>
<input type="checkbox" name="services6" value="Other"< ? if($_POST['services6']=="Other") { echo " checked"; } ?> /> Other
</label> -->
<label>
<span> </span>
<strong>Message/Comments</strong>
<br />
<textarea cols="80" rows="8" name="details"><? echo $_POST['details']; ?></textarea></label>
<label>
<span> </span>
<script type="text/javascript">
var RecaptchaOptions = { theme : 'clean' };
</script>
<?php
require_once('captch.php');
$publickey = "..."; // you got this from the signup page
echo recaptcha_get_html($publickey);
?>
</label>
<label>
<span> </span>
<input type="submit" name="registersubmit" value="Submit" /></label>
</form></div>
<? includecontent($id); ?>
</td>
<!-- new --></tr>
</table>
</td>
</tr>
<tr>
<td width="581" align="right" valign="top" colspan="2"><img src="pictures/spacer.gif" border="0" width="10" height="10"></td>
</tr>
</table>
</td>
</tr>
</table><br />
<img src="pictures/spacer.gif" border="0" width="3" height="3" /></td>
</tr>
</table>
</div><!-- main -->
</div><!-- content -->
<?
include("includes/footer.php");
?>

You should be setting the $to variable, not $my_email.

Related

Send mail form not working

$location ="/contact.php";
if(isset($_POST[$form_names['email']], $_POST[$form_names['subject']], $_POST[$form_names['mess']])){
if($csrf->check_valid('post')){
$email = trim(htmlspecialchars($_POST[$form_names['email']]));
$subject = trim(htmlspecialchars($_POST[$form_names['subject']]));
$mess = trim(htmlspecialchars($_POST[$form_names['mess']]));
if ($email == '' && $subject == '' && $mess == ''){
// $message = "Success";
$headers = "From: {$email}\r\n".
"Content-Type: text/html; charset=ISO-8859-1\r\n";
$current_ip = $_SERVER['REMOTE_ADDR'];
$html_message = nl2br($mess);
$sub = "CONTACT FORM: ".$subject;
//send email
$to = SITE_EMAIL;
$the_mess = "IP: ".$current_ip." <br />
FROM: ".$email."<br />
MESSAGE: <p />"."$html_message";
mail($to, $sub, $the_mess, $headers);
$message = "<div class='alert alert-success'><button type='button' class='close' data-dismiss='alert'>x</button>Thank you, your message has been sent successfully.</div>";
} else {
$message = "<div class='alert alert-danger'><button type='button' class='close' data-dismiss='alert'>x</button>Please complete all required fields.</div>";
}
}
And form:
<form action="<?php echo $location; ?>" method="post" class="form-horizontal" enctype="multipart/form-data">
<label for="subject">Choose Department:</label><br>
<select id="subject" name="<?php echo $form_names['subject']; ?>" class="form-control">
<option value="activation">Account activation</option>
<option value="suspension">Account suspension</option>
<option value="auctions">Auctions</option>
<option value="complaint">Complaints</option>
<option value="others">Others</option>
</select>
<br />
<label for="email">Email Address</label>
<input type="text" class="form-control" name="<?php echo $form_names['email']; ?>" autocomplete="off" value="<?php echo htmlspecialchars($email); ?>" placeholder="Enter your Email Address">
<br />
<label for="email">Please describe your problem</label>
<textarea type="text" class="form-control" style="height:111px;" name="<?php echo $form_names['mess']; ?>" placeholder="Your Message" required="required"><?php echo htmlspecialchars($mess); ?></textarea>
<input class="btn btn-danger" type="submit" name="submit" value="Send Message" />
</form>
When I submit the form, it outputs the second $message:
Please complete all required fields.
I cannot find the issue here. I tried print_r(error_get_last()); and it does not show any errors. Any help would be much appreciated. Thank you very much!
Your condition is if ($email == '' && $subject == '' && $mess == ''){, this means that the mail is sent only if all the fields are empty.
I'm assuming the correct condition should be like if ($email != '' && $subject != '' && $mess != ''){

Posting multiple checkboxes using PHP and sending to an email

I am fairly new with using PHP. I have a form that I am using to send a contact form form a webpage to an email address.
I am having trouble passing multiple checkboxes styled with a comma. For example, if the user picks checkbox1 and checkbox4, the code will be styled: checkbox1, , , checkbox4. I don't want to display the commas, unless the user picks the checkboxes. Let me know if that makes sense or not.
This is the HTML:
<code>
<form id="contact_form" class="contact" method="post" action="email_process.php">
<input class="firstname text" name="firstname" type="text" placeholder="FIRST NAME:" required>
<input class="lastname text" name="lastname" type="text" placeholder="LAST NAME:" required><br><br>
<input class="email text" name="email" type="email" placeholder="EMAIL:" required>
<input class="name text" name="phone" type="tel" placeholder="PHONE NUMBER:" required><br><br>
<label>Would you like to be contacted by:</label>
<input name="how" class="emailbtn radio" type="checkbox" value="Email">
<label>EMAIL</label>
<input name="how2" class="phonebtn radio" type="checkbox" value="Phone">
<label>PHONE NUMBER</label><br><br>
<div class="one">
<label class="margin">EVENT DATE:</label><br>
<input name="month" class="month small" type="number" placeholder="MM">
<input name="day" class="day small" type="number" placeholder="DD">
<input name="year" class="year small" type="number" placeholder="YYYY">
</div>
<div class="one">
<label class="margin">EVENT LOCATION:</label><br>
<input name="location" class="location text" type="text">
</div>
<label>Services we may assist you with:</label><br><br>
<div class="two">
<input name="services" class="chefbtn radio" type="checkbox" value="Personal Chef">
<label>PERSONAL CHEF</label><br>
<input name="services2" class="cateringbtn radio" type="checkbox" value="Private Cooking Classes">
<label>PRIVATE COOKING CLASSES</label>
</div>
<div class="two">
<input name="services3" class="chefbtn radio" type="checkbox" value="Event Catering">
<label>EVENT CATERING</label><br>
<input name="services4" class="cateringbtn radio" type="checkbox" value="Resteraunt Consulting">
<label>RESTERAUNT CONSULTING</label>
</div>
<input name="heard" class="heard text" type="text" placeholder="HOW DID YOU HEAR ABOUT US?">
<textarea name="comments" class="comments" type="text" placeholder="ADDITIONAL COMMENTS:"></textarea>
<input class="submit" type="image" src="../images/contact/s1_submit_btn.png">
</form>
</code>
This is my PHP:
<code>
<?php
//Prefedined Variables
$to = "Enter email here";
// Email Subject
$subject = "Contact from your website.";
// This IF condition is for improving security and Prevent Direct Access to the Mail Script.
if($_POST) {
// Collect POST data from form
$firstname = stripslashes($_POST['firstname']);
$lastname = stripslashes($_POST['lastname']);
$email = stripslashes($_POST['email']);
$how = stripslashes($_POST['how']);
$how2 = stripslashes($_POST['how2']);
$phone = stripslashes($_POST['phone']);
$month = stripslashes($_POST['month']);
$day = stripslashes($_POST['day']);
$year = stripslashes($_POST['year']);
$location = stripslashes($_POST['location']);
$services = stripslashes($_POST['services']);
$services2 = stripslashes($_POST['services2']);
$services3 = stripslashes($_POST['services3']);
$services4 = stripslashes($_POST['services4']);
$heard = stripslashes($_POST['heard']);
$comments = stripslashes($_POST['comments']);
if ( ! empty($how) && ! empty($how2) ) {
$contact_type = $how.', '.$how2;
} elseif (! empty($how)){
$contact_type = $how;
} elseif (! empty($how2)){
$contact_type = $how2;
}
if ( ! empty($services) || ! empty($services2) || ! empty($services3) || ! empty($services4)) {
$contact_type2 = $services. ', ' .$services2. ', ' .$services3. ', ' .$services4;
}
// Collecting all content in HTML Table
$content='<table width="100%">
<tr><td align "center"><b>Contact Details</b></td></tr>
<tr><td>First Name:</td><td> '.$firstname.'</td></tr>
<tr><td>Last Name:</td><td> '.$lastname.'</td></tr>
<tr><td>Email:</td><td> '.$email.' </td></tr>
<tr><td>Phone:</td> <td> '.$phone.'</td></tr>
<tr><td>How Should We Contact You?</td> <td> '.$contact_type.'</td></tr>
<tr><td>Event Date:</td><td> '.$month.' / '.$day.' / '.$year.' </td></tr>
<tr><td>Location:</td> <td> '.$location.'</td></tr>
<tr><td>Which Services Are You Interested In?</td> <td> '.$contact_type2.'</td></tr>
<tr><td>How Did You Hear About Us?</td> <td> '.$heard.'</td></tr>
<tr><td>Comments:</td> <td> '.$comments.'</td></tr>
<tr><td>Date:</td> <td> '.date('d/m/Y').'</td></tr>
</table> ';
// Define email variables
$headers = "From:".$email."\r\n";
$headers .= "Reply-to:".$email."\r\n";
$headers .= 'Content-type: text/html; charset=UTF-8';
if (! empty($how) || ! empty($how2)) {
if (! empty($services) || ! empty($services2) || ! empty($services3) || ! empty($services4)) {
if( ! empty($firstname) && ! empty($lastname) && ! empty($email) && ! empty($phone) && ! empty($month) && ! empty($day) && ! empty($year) && ! empty($location) && ! empty($heard) && ! empty($comments) ) {
// Sending Email
if( mail($to, $subject, $content, $headers) ) {
print "Thank you, I will get back to you shortly!<br>";
return true;
}
else {
print "An error occured and your message could not be sent.";
return false;
}
}
else {
print "An error occured and your message could not be sent.";
return false;
}
}
}
}
</code>
EDIT:
After some research and the right guidance I came across an answer that helped me solve this. If anyone else is having the same problem feel free to refer to this.
<?php
//Prefedined Variables
$to = "Enter email here";
// Email Subject
$subject = "Contact from your website.";
// This IF condition is for improving security and Prevent Direct Access to the Mail Script.
if($_POST) {
// Collect POST data from form
$firstname = stripslashes($_POST['firstname']);
$lastname = stripslashes($_POST['lastname']);
$email = stripslashes($_POST['email']);
$how = 'None';
if(isset($_POST['how']) && is_array($_POST['how']) && count($_POST['how']) > 0){
$selectedHow = implode(', ', $_POST['how']);
}
$phone = stripslashes($_POST['phone']);
$month = stripslashes($_POST['month']);
$day = stripslashes($_POST['day']);
$year = stripslashes($_POST['year']);
$location = stripslashes($_POST['location']);
$services = 'None';
if(isset($_POST['services']) && is_array($_POST['services']) && count($_POST['services']) > 0){
$selectedServices = implode(', ', $_POST['services']);
}
$heard = stripslashes($_POST['heard']);
$comments = stripslashes($_POST['comments']);
// Collecting all content in HTML Table
$content='<table width="100%">
<tr><td align "center"><b>Contact Details</b></td></tr>
<tr><td>First Name:</td><td> '.$firstname.'</td></tr>
<tr><td>Last Name:</td><td> '.$lastname.'</td></tr>
<tr><td>Email:</td><td> '.$email.' </td></tr>
<tr><td>Phone:</td> <td> '.$phone.'</td></tr>
<tr><td>How Should We Contact You?</td> <td> '.$selectedHow.'</td></tr>
<tr><td>Event Date:</td><td> '.$month.' / '.$day.' / '.$year.' </td></tr>
<tr><td>Location:</td> <td> '.$location.'</td></tr>
<tr><td>Which Services Are You Interested In?</td> <td> '.$selectedServices.'</td></tr>
<tr><td>How Did You Hear About Us?</td> <td> '.$heard.'</td></tr>
<tr><td>Comments:</td> <td> '.$comments.'</td></tr>
<tr><td>Date:</td> <td> '.date('d/m/Y').'</td></tr>
</table> ';
// Define email variables
$headers = "From:".$email."\r\n";
$headers .= "Reply-to:".$email."\r\n";
$headers .= 'Content-type: text/html; charset=UTF-8';
if( ! empty($firstname) && ! empty($lastname) && ! empty($email) && ! empty($phone) && ! empty($selectedHow) && ! empty($month) && ! empty($day) && ! empty($year) && ! empty($location) && ! empty($selectedServices) && ! empty($heard) && ! empty($comments) ) {
// Sending Email
if( mail($to, $subject, $content, $headers) ) {
print "Thank you, I will get back to you shortly!<br>";
return true;
}
else {
print "Please go back and make sure that all fields have been filled out.";
return false;
}
}
else {
print "An error occured and your message could not be sent.";
return false;
}
}
<form id="contact_form" class="contact" method="post" action="email_process.php">
<input class="firstname text" name="firstname" type="text" placeholder="FIRST NAME:" required>
<input class="lastname text" name="lastname" type="text" placeholder="LAST NAME:" required><br><br>
<input class="email text" name="email" type="email" placeholder="EMAIL:" required>
<input class="name text" name="phone" type="tel" placeholder="PHONE NUMBER:" required><br><br>
<label>Would you like to be contacted by:</label>
<input name="how[]" class="emailbtn radio" type="checkbox" value="Email">
<label>EMAIL</label>
<input name="how[]" class="phonebtn radio" type="checkbox" value="Phone">
<label>PHONE NUMBER</label><br><br>
<div class="one">
<label class="margin">EVENT DATE:</label><br>
<input name="month" class="month small" type="number" placeholder="MM">
<input name="day" class="day small" type="number" placeholder="DD">
<input name="year" class="year small" type="number" placeholder="YYYY">
</div>
<div class="one">
<label class="margin">EVENT LOCATION:</label><br>
<input name="location" class="location text" type="text">
</div>
<label>Services we may assist you with:</label><br><br>
<div class="two">
<input name="services[]" class="chefbtn radio" type="checkbox" value="Personal Chef">
<label>PERSONAL CHEF</label><br>
<input name="services[]" class="cateringbtn radio" type="checkbox" value="Private Cooking Classes">
<label>PRIVATE COOKING CLASSES</label>
</div>
<div class="two">
<input name="services[]" class="chefbtn radio" type="checkbox" value="Event Catering">
<label>EVENT CATERING</label><br>
<input name="services[]" class="cateringbtn radio" type="checkbox" value="Resteraunt Consulting">
<label>RESTERAUNT CONSULTING</label>
</div>
<input name="heard" class="heard text" type="text" placeholder="HOW DID YOU HEAR ABOUT US?">
<textarea name="comments" class="comments" type="text" placeholder="ADDITIONAL COMMENTS:"></textarea>
<input class="submit" type="image" src="../images/contact/s1_submit_btn.png">
</form>
You need to have the name of those checkboxes as an array. Like:
<label>Would you like to be contacted by:</label>
<input name="how[]" class="emailbtn radio" type="checkbox" value="Email">
<label>EMAIL</label>
<input name="how[]" class="phonebtn radio" type="checkbox" value="Phone">
<label>PHONE NUMBER</label><br><br>
Do same for services:
<input name="services[]" class="chefbtn radio" type="checkbox" value="Personal Chef">
<label>PERSONAL CHEF</label><br>
<input name="services[]" class="cateringbtn radio" type="checkbox" value="Private Cooking Classes">
<label>PRIVATE COOKING CLASSES</label>
</div>
<div class="two">
<input name="services[]" class="chefbtn radio" type="checkbox" value="Event Catering">
<label>EVENT CATERING</label><br>
<input name="services[]" class="cateringbtn radio" type="checkbox" value="Resteraunt Consulting">
Then in your php:
$how = stripslashes($_POST['how']);
// is actually an array and holds its values in a comma separated format
//no need for how2
//The same approach for services: it's also an array now. if you followed the html above
$services = stripslashes($_POST['services']);
It will also be good if you assign different unique error messages unlike you did along
if( ! empty($firstname) && ! empty($lastname) && ! empty($email) && ! empty($phone) && ! empty($how) && ! empty($month) && ! empty($day) && ! empty($year) && ! empty($location) && ! empty($services) && ! empty($heard) && ! empty($comments) ) {
// Sending Email
if( mail($to, $subject, $content, $headers) ) {
print "Thank you, I will get back to you shortly!<br>";
return true;
}
else {
print "An error occured and your message could not be sent.";//here 1
return false;
}
}
else {
print "An error occured and your message could not be sent.";//here 2
return false;
}
}
You can then find out if it's the outer if( ! empty($firstname) && ... or the mail function that is failing
try it with php method array filter and implode:
<?php
$services[] = "test";
$services[] = "";
$services[] = "test";
$services[] = "";
$arr = array_filter($services, function($elem){
return $elem != "";
});
echo implode(", ", $arr);

Using checkboxes to select the to email address in a contact form

I've created an email form that is supposed to be sent to two different email addresses depending on which check box is selected. But am having real trouble trying to make it work, Let me show you what I'm tying to do.
Baring in mind the form actually works great it's just the to email via the checkbox that's failing me.
Please Help!
This is the Form section:
<div id="respond">
<?php echo $response; ?>
<form id="commentForm" method="post" action="#contact2">
<div>
<small>Name:</small>
<input type="text" name="message_name" placeholder="Enter you name..." value="<?php echo $_POST['message_name']; ?>">
<small>Department:</small>
<!-- EDIT || replaced type=checkbox with type=radio -->
<input type="radio" name="sales" value="sales#h-s-c.co.uk" checked/>
<input type="radio"name="lettings" value="lettings#h-s-c.co.uk" />
<small>Email:</small>
<input type="text" name="message_email" placeholder="somebody#email.co.uk" value="<?php echo $_POST['message_email']; ?>">
<small>Phone:</small>
<input class="" type="tel" name="phone_number" placeholder="07912 208 936" value="<?php echo $_POST['phone_number']; ?>">
</div>
<div style="float:right;">
<small>Message:</small>
<textarea type="text" name="message_text" placeholder="I would like further information on..."><?php echo $_POST['message_text']; ?></textarea>
</div>
<small>Human Verification:</small><br>
<input type="text" style="width: 60px;" name="message_human" placeholder="2"> + 3 = 5</label>
<input type="hidden" name="submitted" value="1">
<input class="" type="submit" value="submit"/>
</form>
</div>
Then the php to send the form looks like this:
<?php
//Include email and to name
$admin_email = $_POST[$email_address];//EDIT || changed to new value $email_address
$block = "Test";
//Remove this section
//foreach($_POST['check'] as $value) {
// $checkbox .= "$value\n";
//}
?>
<?php
//response generation function
$response = "";
//function to generate response
function generate_response($type, $message){
global $response;
if($type == "success") $response = "<div class='success'>{$message}</div>";
else $response = "<div class='error'>{$message}</div>";
}
//response messages
$not_human = "Human verification incorrect.";
$missing_content = "Please supply all information.";
$email_invalid = "Email Address Invalid.";
$message_unsent = "Message was not sent. Try Again.";
$message_sent = "Thanks! Your message has been sent.";
//user posted variables
$name = $_POST['message_name'];
$email = $_POST['message_email'];
$phone = $_POST['phone_number'];
$message = $_POST['message_text'];
$human = $_POST['message_human'];
//php mailer variables
$to = $admin_email;
$subject = "Someone sent a message from {$block}";
$headers = 'From: '. $email . "\r\n" .
'Reply-To: ' . $email . "\r\n";
$tel = 'Contact no: ' . $phone;
if(!$human == 0){
if($human != 2) generate_response("error", $not_human); //not human!
else {
//validate email
if(!filter_var($email, FILTER_VALIDATE_EMAIL))
generate_response("error", $email_invalid);
else //email is valid
{
//validate presence of name and message
if(empty($name) || empty($message)){
generate_response("error", $missing_content);
}
else //ready to go!
{
$sent = mail($to, $subject, $message . $tel , $headers);
if($sent) generate_response("success", $message_sent); //message sent!
else generate_response("error", $message_unsent); //message wasn't sent
}
}
}
}
else if ($_POST['submitted']) generate_response("error", $missing_content);
?>
When the form is submitted checkboxes does not provide their value to the server. Check boxes only have a value on if they are checked. use a radiobutton or a select box instead.
Checkbox does not send string value, just boolean values for checkbox identifier.
Add in code a new condition
If CHECKED then use email else blank for both checkbox.
<?php
//Include email and to name
$admin_email = $_POST[$checkbox]; // no element with name 'checkbox'
$block = "Test";
// no element with name 'check'
foreach($_POST['check'] as $value) {
$checkbox .= "$value\n";
}
?>
these are main issue.
If you want to send mail to any one from the two options then use select, and in value of option provide email id
//HTML CODE
<select name="to_email">
<option value="sales#xxxx">Sales</option>
<option value="lettings#xxxx">Lettings</option>
</select>
PHP CODE
<?php
$admin_email = $_POST['to_email']; // this will get you the selected email id
?>
let me know if you have any queries.
*<form id="requestform" name="requestform" action="enquiry.php" class="col-xs-12" method="post">
<div class="form-wrapper">
<div class="col-xs-12">
<div class="field col-xs-6">
<label class="formlabel"> Email </label>
<input class="textfield" data-required="true" type="email" name="email" />
</div>
<div class="field col-xs-6">
<label class="formlabel"> Phone </label>
<input class="textfield" data-required="true" type="text" name="phone" />
</div>
</div>
<div class="clear"></div>
<div class="col-xs-12">
<div class="field col-xs-6">
<label class="formlabel"> Details </label>
<textarea class="textfield textarea" type="textarea" data-required="true" name="details"/></textarea >
</div>
<div class="field emailfunc col-xs-6">
<label class="formlabel"> What can we help you with ? </label>
<span>
<input name="interested" id="logistics" value="logistics" onchange="" type="checkbox">
<label class="inline" >Logistics</label>
</span>
<span>
<input name="interested" id="sales" value="sales" onchange="" type="checkbox">
<label class="inline" >Sales</label>
</span>
<span>
<input name="interested" id="customer" value="customer" onchange="" type="checkbox">
<label class="inline" >Customer</label>
</span>
</div>
<div class="clear"></div>
</div>
<div class="clear"></div>
</div>
<div class="col-xs-12">
<div class="field col-xs-6">
<input class="submit" type="submit" value="<?php echo Mage::helper('contacts')->__('Send Enquiry') ?>" name="submit">
</div>
</div>
<div class="clear"></div>
</form>
<?php
//enquiry.php
$email=$_REQUEST['email'];
$phone=$_REQUEST['phone'];
$details=$_REQUEST['details'];
$interested=$_REQUEST['interested'];
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= "From: \"Request a Quote\" <fakhruddinsouq>\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$message = '<html><head><title>Fakhruddin Souq</title></head><body>
<div style="color:#006A93; width:auto; height:auto; background-color:#eeeeee; margin:0px auto;">
<fieldset style=" border-color:#006A93; border-style:double;">
<legend align="center" style="font-family:Arial, Helvetica, sans-serif; font-size:18px; text-decoration:underline;">Request a Quote</legend>
<head><title>Fakhruddin Souq</title></head>
<table border="0" cellpadding="0" cellspacing="4" align="left" width="100%" height="100%" style="color:#006A93; font-weight:bold; font-size:12px; font-family:Arial, Helvetica, sans-serif;">
<td align="left" valign="top">Email: </td>
<td align="left" valign="top">'.$email.'</td>
</tr>
<tr>
<td align="left" valign="top">Phone: </td>
<td align="left" valign="top">'.$phone.'</td>
</tr>
<tr>
<td align="left" valign="top"> Product Details: </td>
<td align="left" valign="top">'.$details.'</td>
</tr>
<tr>
<td colspan="2" align="left" valign="top" style="font-size:14px;">Regards</td>
</tr>
</table>
<span style="clear:both; float:left; font-size:14px; padding-left:4px; padding-top:10px; font-family:Arial, Helvetica, sans-serif;">Posted Date & Time:'.date('m/d/Y H:i:s').'</span>
</fieldset>
</div>
</body>
</html>';
if($interested == 'logistics') {
$to = "abc#email.com";
}
else if($interested == 'sales') {
$to = "def#email.com";
}
else if($interested == 'customer') {
$to = "imemail#email.com";
}
else if($interested == 'logistics' && $interested == 'sales' && $interested == 'customer'){
$to = "abc#email.com,def#email.com,imemail#email.com";
}
else if($interested == 'logistics' && $interested == 'sales'){
$to = "abc#email.com,def#email.com";
}
else if($interested == 'logistics' && $interested == 'customer') {
$to = "abc#email.com,imemail#email.com";
}
else if($interested == 'sales' && $interested == 'customer') {
$to = "def#email.com,imemail#email.com";
}
else {
$to ="imemail#email.com";
}
if (mail($to,'Mail From '.$name,$message,$headers)){
print json_encode(array('type'=>'done', 'text' => 'Thank You For Your Enquiry'));
exit;
}
else {
print json_encode(array('type'=>'done', 'text' => 'Sorry Email is not sent'));
exit;
}
?>*

Submit button checking mandatory fields before opening new window

I've a HTML 5 form with mandatory fields etc. The submit button when clicked checks for mandatory fields before submitting. While I've changed the behavior to open a link in another window, I can't make the form check the mandatory fields and send the links after this is done.
I need the form to also check if the fields have been filled and then process with validation and external link but rather not have the link opened while the user skip from filling it.
My form's codes read as follows:
<?php
//init variables
$cf = array();
$sr = false;
if(isset($_SESSION['cf_returndata'])){
$cf = $_SESSION['cf_returndata'];
$sr = true;
}
?>
<ul id="errors" class="<?php echo ($sr && !$cf['form_ok']) ? 'visible' : ''; ?>">
<li id="info">There were some problems with your form submission:</li>
<?php
if(isset($cf['errors']) && count($cf['errors']) > 0) :
foreach($cf['errors'] as $error) :
?>
<li><?php echo $error ?></li>
<?php
endforeach;
endif;
?>
</ul>
<p id="success" class="<?php echo ($sr && $cf['form_ok']) ? 'visible' : ''; ?>">Thanks for your message! We will get back to you ASAP!</p>
<form method="post" action="process.php">
<label for="name">Name: <span class="required">*</span></label>
<input type="text" id="name" name="name" value="<?php echo ($sr && !$cf['form_ok']) ? $cf['posted_form_data']['name'] : '' ?>" placeholder="John Doe" required autofocus />
<label for="email">Email Address: <span class="required">*</span></label>
<input type="email" id="email" name="email" value="<?php echo ($sr && !$cf['form_ok']) ? $cf['posted_form_data']['email'] : '' ?>" placeholder="johndoe#example.com" required />
<label for="telephone">Telephone: </label>
<input type="tel" id="telephone" name="telephone" value="<?php echo ($sr && !$cf['form_ok']) ? $cf['posted_form_data']['telephone'] : '' ?>" />
<label for="enquiry">Enquiry: </label>
<select id="enquiry" name="enquiry">
<option value="Choose" selected>Choose</option>
<option value="Purchase">Purchase</option>
<option value="Distribution">Distribution</option>
<option value="Inquire">Inquire</option>
</select>
<label for="message">Message: <span class="required">*</span></label>
<textarea id="message" name="message" placeholder="Your message must be greater than 20 charcters" required data-minlength="20"><?php echo ($sr && !$cf['form_ok']) ? $cf['posted_form_data']['message'] : '' ?></textarea>
<span id="loading"></span>
<input type="submit" value="Submit" id="submit-button" Link" onClick="window.open ('https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=G6ZNL8H4JXBB8', 'newwindow')"/>
<p id="req-field-desc"><span class="required">*</span> indicates a required field</p>
</form>
<?php unset($_SESSION['cf_returndata']); ?>
</div>
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script>!window.jQuery && document.write(unescape('%3Cscript src="js/libs/jquery-1.5.1.min.js"%3E%3C/script%3E'))</script>
<script src="js/plugins.js"></script>
<script src="js/script.js"></script>
<!--[if lt IE 7 ]>
<script src="js/libs/dd_belatedpng.js"></script>
<script> DD_belatedPNG.fix('img, .png_bg');</script>
<![endif]-->
And my Process.php file is as follows
<?php
if( isset($_POST) ){
//form validation vars
$formok = true;
$errors = array();
//sumbission data
$ipaddress = $_SERVER['REMOTE_ADDR'];
$date = date('d/m/Y');
$time = date('H:i:s');
//form data
$name = $_POST['name'];
$email = $_POST['email'];
$telephone = $_POST['telephone'];
$enquiry = $_POST['enquiry'];
$message = $_POST['message'];
//validate form data
//validate name is not empty
if(empty($name)){
$formok = false;
$errors[] = "You have not entered a name";
}
//validate email address is not empty
if(empty($email)){
$formok = false;
$errors[] = "You have not entered an email address";
//validate email address is valid
}elseif(!filter_var($email, FILTER_VALIDATE_EMAIL)){
$formok = false;
$errors[] = "You have not entered a valid email address";
}
//validate message is not empty
if(empty($message)){
$formok = false;
$errors[] = "You have not entered a message";
}
//validate message is greater than 20 charcters
elseif(strlen($message) < 20){
$formok = false;
$errors[] = "Your message must be greater than 20 characters";
}
//send email if all is ok
if($formok){
$headers = "From: myemail#mail.com" . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$emailbody = "<p>You have recieved a new message from the enquiries form on your website.</p>
<p><strong>Name: </strong> {$name} </p>
<p><strong>Email Address: </strong> {$email} </p>
<p><strong>Telephone: </strong> {$telephone} </p>
<p><strong>Enquiry: </strong> {$enquiry} </p>
<p><strong>Message: </strong> {$message} </p>
<p>This message was sent from the IP Address: {$ipaddress} on {$date} at {$time}</p>";
mail("myemail#mail.com","New Enquiry",$emailbody,$headers);
}
//what we need to return back to our form
$returndata = array(
'posted_form_data' => array(
'name' => $name,
'email' => $email,
'telephone' => $telephone,
'enquiry' => $enquiry,
'message' => $message
),
'form_ok' => $formok,
'errors' => $errors
);
//if this is not an ajax request
if(empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) !== 'xmlhttprequest'){
//set session variables
session_start();
$_SESSION['cf_returndata'] = $returndata;
//redirect back to form
header('location: ' . $_SERVER['HTTP_REFERER']);
}
}
You can do all in single php file . (say form_disp_process.php)
<?php
if( isset($_POST) )
{
// check validation set formok=true or false
if($formok)
{
//mail data
// if u want to redirect user to new welcome page after mailing
echo "
<script language='JavaScript'>
window.location = 'welcomepage.php';
//window.open ('https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=G6ZNL8H4JXBB8', 'newwindow')"
</script>
";
}
}
else
{
//init variables
?>
<ul id="errors" class="<?php echo ($sr && !$cf['form_ok']) ? 'visible' : ''; ?>">
<li id="info">There were some problems with your form submission:</li>
<?php
if(isset($cf['errors']) && count($cf['errors']) > 0) :
foreach($cf['errors'] as $error) :
?>
<li><?php echo $error ?></li>
<?php
endforeach;
endif;
?>
</ul>
<p id="success" class="<?php echo ($sr && $cf['form_ok']) ? 'visible' : ''; ?>">Thanks for your message! We will get back to you ASAP!</p>
<form method="post" action="form_disp_process.php">
<label for="name">Name: <span class="required">*</span></label>
<input type="text" id="name" name="name" value="<?php echo ($sr && !$cf['form_ok']) ? $cf['posted_form_data']['name'] : '' ?>" placeholder="John Doe" required autofocus />
<label for="email">Email Address: <span class="required">*</span></label>
<input type="email" id="email" name="email" value="<?php echo ($sr && !$cf['form_ok']) ? $cf['posted_form_data']['email'] : '' ?>" placeholder="johndoe#example.com" required />
<label for="telephone">Telephone: </label>
<input type="tel" id="telephone" name="telephone" value="<?php echo ($sr && !$cf['form_ok']) ? $cf['posted_form_data']['telephone'] : '' ?>" />
<label for="enquiry">Enquiry: </label>
<select id="enquiry" name="enquiry">
<option value="Choose" selected>Choose</option>
<option value="Purchase">Purchase</option>
<option value="Distribution">Distribution</option>
<option value="Inquire">Inquire</option>
</select>
<label for="message">Message: <span class="required">*</span></label>
<textarea id="message" name="message" placeholder="Your message must be greater than 20 charcters" required data-minlength="20"><?php echo ($sr && !$cf['form_ok']) ? $cf['posted_form_data']['message'] : '' ?></textarea>
span id="loading"></span>
<input type="submit" value="Submit" id="submit-button" Link" />
<p id="req-field-desc"><span class="required">*</span> indicates a required field</p>
</form>
<?php unset($_SESSION['cf_returndata']); ?>
</div>
</div>
<?php
} //else close
?>
Since you mentioned HTML5 .I am adding another answer
Use Javascript to validate your form and then redirect to paypal site
Mistakes you made :
You have used attribute "required" for mandatory fields but have you have to give value .
Like this required="required"
Reference : http://www.w3schools.com/html5/att_textarea_required.asp
There is no attribute called data-minlength for textarea
Reference : http://www.w3schools.com/html5/tag_textarea.asp
Code HTML5 + JavaScript :
<head>
<script type="text/javascript">
function checklength()
{
var x=document.forms["myform"]["message"].value;
if(x.length < 20)
{
alert("Your message must be greater than 20 charcter");
document.getElementById('errors').innerHTML = 'Your message must be greater than 20 charcter';
return false;
}
return true;
}
</script>
</head>
<body>
<div id= "errors"> </div>
<form method="post" name="myform" onsubmit="return checklength();" action="mail_me_and_redirect_to_paypal.php" >
<label for="name">Name: <span class="required">*</span></label>
<input type="text" id="name" name="name" required="required" value="sdfdf" placeholder="John Doe" autofocus />
<label for="email">Email Address: <span class="required">*</span></label>
<input type="email" id="email" name="email" required="required" value="dsfds#sdf.com" placeholder="johndoe#example.com" />
<label for="telephone">Telephone: </label>
<input type="tel" id="telephone" name="telephone" required="required" value="werwe" />
<label for="enquiry">Enquiry: </label>
<select id="enquiry" name="enquiry">
<option value="Choose" selected>Choose</option>
<option value="Purchase">Purchase</option>
<option value="Distribution">Distribution</option>
<option value="Inquire">Inquire</option>
</select>
<label for="message">Message: <span class="required">*</span></label>
<textarea id="message" name="message" placeholder="Your message must be greater than 20 charcters" required="required" ></textarea>
<input type="submit" value="Submit" />
<p id="req-field-desc"><span class="required">*</span> indicates a required field</p>
</form>
</body>

reCaptcha integration with php

I'm building a contact us page that also uses a reCaptcha, but im having a few issues with it. I fill in all of the fields in the contact form and the correct reCaptcha words, but the form does not submit. I'm assuming this is something to do with the validation, but wondered if someone might be able to spot where i'm going wrong?
The PHP code at the top of my page looks like this;
<?php include('includes/session.php');
$err = '';
$success = '';
if(isset($_POST["docontact"]) && $_POST["docontact"] == "yes") {
//get form details
$form = new stdClass();
$form->name = sanitizeOne($_POST["name"], "str");
$form->email = sanitizeOne($_POST["email"], "str");
$form->phone = sanitizeOne($_POST["phone"], "str");
$form->mysevenprog = sanitizeOne($_POST["mysevenprog"], "str");
$form->enquiry = sanitizeOne($_POST["enquiry"], "str");
$form->howfindsite = sanitizeOne($_POST["howfindsite"], "str");
//Check for errors (required: name, email, enquiry)
if($form->name == "") {
$err .= '<p class="warning">Please enter your name!</p>';
}
if($form->email == "") {
$err .= '<p class="warning">Please enter your email address!</p>';
}
if($form->enquiry == "") {
$err .= '<p class="warning">Please supply an enquiry message!</p>';
}
//Send Email
if($err == "") {
$mailer = new BlueMailer();
$mailer->AddAddress(Configuration::getVar("developer_email"), Configuration::getVar("admin_email_name"));
include('templates/email/contact-us-admin.php');
if(!$mailer->Send()) {
$err .= "<p>There was an error sending submitting your request!, Please try again later.";
} else {
$success = 'thanks';
}
}
} else {
//Initialise empty variables
$form = new stdClass();
$form->name = "";
$form->email = "";
$form->phone = "";
$form->mysevenprog = "";
$form->enquiry = "";
$form->howfindsite = "";
}
?>
And then in the body of my page I have the form as follows;
<?php if($err != "") : ?>
<div class="error">
<?php echo $err; ?>
</div>
<?php endif; ?>
<?php if($success == 'thanks') : ?>
<h3>Thank you for your enquiry</h3>
<p>Your enquiry has been successfully sent. Someone will contact you shortly.</p>
<?php else: ?>
<h3>If you are looking to advertise with us, have some feedback about some of our programming or want to say 'Hi' please use the fields below</h3>
<form name="contactus" id="contactus" method="post" action="<?php echo $_SERVER['SCRIPT_NAME'] ?>">
<ul>
<li><label for="name">Your name: *</label> <input name="name" id="name" class="textbox" style="width: 75%;" type="text" value="<?php echo $form->name ?>" /></li>
<li><label for="email">Email address: *</label> <input name="email" id="email" class="textbox" style="width: 75%;" type="text" value="<?php echo $form->email ?>" /></li>
<li><label for="phone">Telephone:</label> <input name="phone" id="phone" class="textbox" style="width: 75%;" type="text" value="<?php echo $form->phone ?>" /></li>
<li><label for="mysevenprog">My Seven programme</label> <input name="mysevenprog" class="textbox" style="width: 75%;" type="text" value="<?php echo $form->mysevenprog ?>" /></li>
<li><label for="enquiry">Enquiry/Message: *</label> <textarea name="enquiry" class="textarea" rows="5" cols="30" style="width: 75%;" id="enquiry"><?php echo $form->enquiry ?></textarea></li>
<li><label for="howfindsite">How did you find out about our site?</label> <input name="howfindsite" id="howfindsite" class="textbox" style="width: 75%;" type="text" value="<?php echo $form->howfindsite ?>" /></li>
<li>
<?php
require_once('recaptchalib.php');
// Get a key from http://recaptcha.net/api/getkey
$publickey = "";
$privatekey = "";
# the response from reCAPTCHA
$resp = null;
# the error code from reCAPTCHA, if any
$error = null;
# was there a reCAPTCHA response?
if ($_POST["recaptcha_response_field"]) {
$resp = recaptcha_check_answer ($privatekey,
$_SERVER["REMOTE_ADDR"],
$_POST["recaptcha_challenge_field"],
$_POST["recaptcha_response_field"]);
if ($resp->is_valid) {
echo "You got it!";
} else {
# set the error code so that we can display it
$error = $resp->error;
}
}
echo recaptcha_get_html($publickey, $error);
?>
</li>
<li><input type="submit" value="Submit Form" class="button" /></li>
</ul>
<input type="hidden" name="docontact" value="yes" />
</form>
<?php endif; ?>
The form gets rendered like this in the browser;
<form name="contactus" id="contactus" method="post" action="/contact-us2.php">
<ul>
<li><label for="name">Your name: *</label> <input name="name" id="name" class="textbox" style="width: 75%;" type="text" value="" /></li>
<li><label for="email">Email address: *</label> <input name="email" id="email" class="textbox" style="width: 75%;" type="text" value="" /></li>
<li><label for="phone">Telephone:</label> <input name="phone" id="phone" class="textbox" style="width: 75%;" type="text" value="" /></li>
<li><label for="mysevenprog">My Seven programme</label> <input name="mysevenprog" class="textbox" style="width: 75%;" type="text" value="" /></li>
<li><label for="enquiry">Enquiry/Message: *</label> <textarea name="enquiry" class="textarea" rows="5" cols="30" style="width: 75%;" id="enquiry"></textarea></li>
<li><label for="howfindsite">How did you find out about our site?</label> <input name="howfindsite" id="howfindsite" class="textbox" style="width: 75%;" type="text" value="" /></li>
<li>
<script type="text/javascript" src="http://api.recaptcha.net/challenge?k=XXXXXXXXXXXXXXXXXXX"></script>
<noscript>
<iframe src="http://api.recaptcha.net/noscript?k=XXXXXXXXXXXXXXXXXXXX" height="300" width="500" frameborder="0"></iframe><br/>
<textarea name="recaptcha_challenge_field" rows="3" cols="40"></textarea>
<input type="hidden" name="recaptcha_response_field" value="manual_challenge"/>
</noscript>
</li>
<li><input type="submit" value="Submit Form" class="button" /></li>
</ul>
<input type="hidden" name="docontact" value="yes" />
</form>
Just use Zend_Service_ReCaptcha. You'll integrate this service just with few lines:
//Creating instance
$recaptcha = new Zend_Service_ReCaptcha($pubKey, $privKey);
//Display output
echo $recaptcha->getHTML();
//Handling input
$result = $recaptcha->verify(
$_POST['recaptcha_challenge_field'],
$_POST['recaptcha_response_field']
);
//And finally validate captcha
if ($result->isValid()) {
//Cool!
}
Take a look at Using reCAPTCHA to stop spam in PHP.

Categories