Validating 'Price' (double) form input PHP [duplicate] - javascript

This question already has answers here:
checking if a number is float in PHP
(5 answers)
Closed 7 years ago.
Hi i'm trying to validate user input on a form using PHP.
I have managed to validate text, numeric and year input but can't get price to work.
I create error variables at the top of my code:
$titleErr = ""; $developerErr = ""; $releaseErr = ""; $stockErr = ""; $priceErr = "";
I then validate the input and assign a message to the variable if needs be:
if (!preg_match("/^[a-zA-Z ]*$/",$title)) {
$titleErr = "Invalid input, only letters and white space allowed.";
} else if (!preg_match("/^[a-zA-Z ]*$/",$developer)){
$developerErr = "Invalid input, only letters and white space allowed.";
} else if ($release<1990 || $release>2020){
$releaseErr = "Invalid input, enter a year between 1990 & 2020.";
} else if (!is_numeric($stock)){
$stockErr = "Invalid input, only numbers allowed.";
} else if (!is_float($price)){
$priceErr = "Invalid input, only doubles allowed.";
}
The first 4 statements validate input perfectly. However the last one that is checking if the input is a float (for price e.g. 10.99) seems to return the error message when I enter correct input.
This is my form:
<form class ="form-horizontal" role="form" id="add" name="add" action="?" method="post">
<div class="form-group">
<label class="control-label col-sm-2">Title</label> <div class="col-sm-10"><input class="form-control" id="addFormTitle" name="title" type="text"> <span class="error"><?php echo $titleErr;?></span></div>
</div>
<div class="form-group">
<label class="control-label col-sm-2">Developer</label> <div class="col-sm-10"><input class="form-control" id="addFormDeveloper" name="developer" type="text"> <span class="error"><?php echo $developerErr;?></span></div>
</div>
<div class="form-group">
<label class="control-label col-sm-2">Release (Year Format/YYYY)</label> <div class="col-sm-10"><input class="form-control" id="addFormRelease" name="release" type="text"> <span class="error"><?php echo $releaseErr;?></span></div>
</div>
<div class="form-group">
<label class="control-label col-sm-2">Stock</label> <div class="col-sm-10"><input class="form-control" id="addFormStock" name="stock" type="text"> <span class="error"><?php echo $stockErr;?></span></div>
</div>
<div class="form-group">
<label class="control-label col-sm-2">Price (&#163)</label> <div class="col-sm-10"><input class="form-control" id="addFormPrice" name="price" type="text"> <span class="error"><?php echo $priceErr;?></span></div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-default" name="addSubmit" value="Add product">Submit</button>
</div>
</div>
</form>

You can use floatval function to get the float value of a variable and then check whether it's a float value or not, like this:
if(is_float(floatval($price))){
echo "float value";
}else{
echo "not a float value";
}
Edited:
In your code you can do something like this:
if (!preg_match("/^[a-zA-Z ]*$/",$title)) {
$titleErr = "Invalid input, only letters and white space allowed.";
} else if (!preg_match("/^[a-zA-Z ]*$/",$developer)){
$developerErr = "Invalid input, only letters and white space allowed.";
} else if ($release<1990 || $release>2020){
$releaseErr = "Invalid input, enter a year between 1990 & 2020.";
} else if (!is_numeric($stock)){
$stockErr = "Invalid input, only numbers allowed.";
} else if (!is_float(floatval($price))){
$priceErr = "Invalid input, only doubles allowed.";
}

Related

How to check input field pattern validation on if else condition javascript?

How to check input field pattern validation on if else condition javascript? to show message div for valid and Invalid on button submit on type for pattern validation?
function myFunction(element) {
if (document.getElementById("smsno").value.length == 0) {
document.getElementById("sms_ntvalidate").style.display = "block";
document.getElementById("sms_validate").style.display = "none";
} else {
document.getElementById("sms_validate").style.display = "block";
document.getElementById("sms_ntvalidate").style.display = "none";
}
}
<div class="form-row">
<div class="form-group col-md-6 smsForm">
<label for="contact1">SMS No.<span style="color:#ff0000">*</span></label>
<input type="tel" class="form-control" name="smsno" id="smsno"
placeholder="SMS No." pattern="^(00|\+)[1-9]{1}([0-9][\s]*){9,16}$"
required onkeyup="myFunction(this)" />
<div class="custm-valid" id="sms_validate" style="display:none;">Valid.</div>
<div class="custm-invalid" id="sms_ntvalidate" style="display:none;">Please enter valid contact no.</div>
</div>
<div class="form-group col-md-6 whatsappForm">
<label for="contact2">WhatsApp No.<span style="color:#ff0000">*</span></label>
<input type="text" class="form-control" name="whtspno" id="whtspno"
placeholder="WhatsApp No." pattern="^(00|\+)[1-9]{1}([0-9][\s]*){9,16}$"
required />
<div class="custm-valid" id="whts_validate"style="display:none;">Valid.</div>
<div class="custm-invalid" id="whts_ntvalidate" style="display:none;">Please enter valid contact no.</div>
</div>
</div>
Your pattern is number you can use custom js for thise validation like
document.getElementById("smsno").value.forEach((value)=>{ if(value >== 0 && value <== 9) { // Condition} else { //Wrong Pattern condition } );
The forEach checkes the every single element on input

How to I get my html email form to validate using javascript before sending it to the php script for sending

I have an html email enquiry form that validates the form fields using javascript and displays the error messages but it still continues and actually submits and emails the enquiry form anyway using a php script. I am trying to trap the error(s) before the actual php script that sends the email is executed. Basically the correct error messages are displayed for each form field when I click send message but instead of allowing me to enter the correct information it continues and executes the php send script and sends the email anyway. If any fields are incorrect I need it to stay on the input screen until the fields are entered correctly.
Here is the validate function code :-
<script>
function validate(){
var name=document.f1.name.value;
var subject=document.f1.subject.value;
var arrivaldate=document.f1.arrivaldate.value;
var departuredate=document.f1.departuredate.value;
var email=document.f1.email.value;
var stay=document.f1.stay.value;
var message=document.f1.message.value;
var status=false;
if(name.length<4){
document.getElementById("nameloc").innerHTML= "Please enter at least 4 chars";
document.getElementById("nameloc").style.color= "red";
status=false;
}else{
document.getElementById("nameloc").innerHTML="";
status=true;
}
if(subject.length<8){
document.getElementById("subjloc").innerHTML= "Please enter at least 8 chars of subject";
document.getElementById("subjloc").style.color= "red";
status=false;
}else{
document.getElementById("subjloc").innerHTML="";
status=true;
}
if(arrivaldate==""){
document.getElementById("arrivaldateloc").innerHTML= "Please select Arrival date ";
document.getElementById("arrivaldateloc").style.color= "red";
status=false;
}else{
document.getElementById("arrivaldateloc").innerHTML="";
status=true;
}
if(departuredate==""){
document.getElementById("departuredateloc").innerHTML= "Please select Departure date ";
document.getElementById("departuredateloc").style.color= "red";
status=false;
}else{
document.getElementById("departuredateloc").innerHTML="";
status=true;
}
if(email==""){
document.getElementById("emailloc").innerHTML= "Please enter a valid email";
document.getElementById("emailloc").style.color= "red";
status=false;
}else{
document.getElementById("emailloc").innerHTML="";
status=true;
}
if(stay==""){
document.getElementById("stayloc").innerHTML= "Please enter a Stay field max length 30 chars";
document.getElementById("stayloc").style.color= "red";
status=false;
}else{
document.getElementById("stayloc").innerHTML="";
status=true;
}
if(message==""){
document.getElementById("messageloc").innerHTML= "Please enter a message field";
document.getElementById("messageloc").style.color= "red";
status=false;
}else{
document.getElementById("messageloc").innerHTML="";
status=true;
}
return status;
}
</script>
Here is the form code:-
<form id="contact-form" action="http://www.cambodia.me.uk/krdc03/contact_mail.php" method="post" name="f1" onsubmit="return validate()">
<div class="col-md-6">
<div class="form-group">
<label>
Name</label>
<input type="text" name="name" class="form-control" placeholder="Your Name"/>
<span id="nameloc"></span>
</div>
<div class="form-group">
<label for="subject">
Our Reference</label>
<input type="text" class="form-control" name="subject" placeholder="Web Enquiry Form" value="Web Enquiry Form" readonly/>
<span id="subjloc"></span>
</div>
<div class="form-group">
<label for="Adate">
Arrival Date</label>
<input type="text" class="startdate form-control" size="30" name="arrivaldate" placeholder="dd/mm/yyyy" />
<span id="arrivaldateloc"></span>
</div>
<div class="form-group">
<label for="Ddate">
Departure Date</label>
<input type="text" class="startdate form-control" name="departuredate" size="30" placeholder="dd/mm/yyyy" />
<span id="departuredateloc"></span>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="email">
Email Address</label>
<div class="form-group">
<input type="email" class="form-control" name="email" placeholder="Your Email"/>
<span id="emailloc"></span>
</div>
</div>
<div class="form-group">
<label for="stay">
How did you hear about us</label>
<input type="text" class="form-control" name="stay" maxlength="30" placeholder="ie Google, Tripadvisor etc"/>
<span id="stayloc"></span>
</div>
<div class="form-group">
<label for="message">
Message</label>
<textarea class="form-control" name="message" rows="4" placeholder="">
</textarea>
<span id="messageloc"></span>
</div>
</div>
<div class="col-md-12">
<button type="submit" name="submit" class="btn btn-skin pull-right">
Send Message</button>
</div>
</form>
Many thanks
OK, found the error was in my validate function. Answering here as it may help someone else. I was setting status (therefore the return value) to true each field that passed. This meant if last field passed all the criteria the status for the whole form was set back to true. Fixed it by setting initial value of status = true and commenting out all the other instances that reset it to true. Modified function code below - other code remains unchanged:-
<script>
function validate(){
var name=document.f1.name.value;
var subject=document.f1.subject.value;
var arrivaldate=document.f1.arrivaldate.value;
var departuredate=document.f1.departuredate.value;
var email=document.f1.email.value;
var stay=document.f1.stay.value;
var message=document.f1.message.value;
var status=true;
if(name.length<4){
document.getElementById("nameloc").innerHTML= "Please enter at least 4 chars";
document.getElementById("nameloc").style.color= "red";
status=false;
}else{
document.getElementById("nameloc").innerHTML="";
//status=true;
}
if(subject.length<8){
document.getElementById("subjloc").innerHTML= "Please enter at least 8 chars of subject";
document.getElementById("subjloc").style.color= "red";
status=false;
}else{
document.getElementById("subjloc").innerHTML="";
//status=true;
}
if(arrivaldate==""){
document.getElementById("arrivaldateloc").innerHTML= "Please select Arrival date ";
document.getElementById("arrivaldateloc").style.color= "red";
status=false;
}else{
document.getElementById("arrivaldateloc").innerHTML="";
//status=true;
}
if(departuredate==""){
document.getElementById("departuredateloc").innerHTML= "Please select Departure date ";
document.getElementById("departuredateloc").style.color= "red";
status=false;
}else{
document.getElementById("departuredateloc").innerHTML="";
//status=true;
}
if(email==""){
document.getElementById("emailloc").innerHTML= "Please enter a valid email";
document.getElementById("emailloc").style.color= "red";
status=false;
}else{
document.getElementById("emailloc").innerHTML="";
//status=true;
}
if(stay==""){
document.getElementById("stayloc").innerHTML= "Please enter a Stay field max length 30 chars";
document.getElementById("stayloc").style.color= "red";
status=false;
}else{
document.getElementById("stayloc").innerHTML="";
//status=true;
}
if(message==""){
document.getElementById("messageloc").innerHTML= "Please enter a message field";
document.getElementById("messageloc").style.color= "red";
status=false;
}else{
document.getElementById("messageloc").innerHTML="";
//status=true;
}
return status;
}
</script>

Trying to use PHP and Ajax to do form validation, not working

I have been trying to figure out how to do php form validation and using ajax to get the results back so I don't have to refresh page. I'm new to ajax and having a hard time.
This is my registration.php form
<h1>Sign Up</h1>
<form id="registration_form" method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="first_name">First name</label>
<input type="text" class="form-control" id="first_name" name="first_name" onblur="validate('first_name', this.value)" placeholder="First name">
</div>
</div>
<div id="textFirstName" class="col-md-6">
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="last_name">Last name</label>
<input type="text" class="form-control" id="last_name" name="last_name" onblur="validate('last_name', this.value)" placeholder="Last name">
</div>
</div>
<div id="textLastName" class="col-md-6">
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="email1">Email address</label>
<input type="email" class="form-control" id="email1" name="email1" onblur="validate('email1', this.value)" placeholder="Email">
</div>
</div>
<div id="textEmail" class="col-md-6">
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="Password1">Password</label>
<input type="password" class="form-control" id="password1" name="password1" onblur="validate('password1', this.value)" placeholder="Password">
</div>
</div>
<div id="textPass1" class="col-md-6">
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="Password2">Confirm Password</label>
<input type="password" class="form-control" id="password2" name="password2" onblur="validate('password2', this.value)" placeholder="Retype Password">
</div>
</div>
<div id="textPass2" class="col-md-6">
</div>
</div>
<div class="row">
<div class="col-md-6">
<button type="submit" class="btn btn-default">Submit</button>
</div>
<div class="col-md-6">
</div>
</div>
</form>
This is my validation php script:
<?php
$value = $_POST['query'];
$formfield = $_POST['field'];
// Check Valid or Invalid first name when user enters user name in username input field.
if ($formfield == "first_name") {
if (strlen($value) < 1) {
echo "<p style=\"color:red\">Error: Must be 1+ letters</p>";
} else {
echo "<p style=\"color:green\">Valid</p>";
$_SESSION['reg']['first_name'] = $value;
}
}
if ($formfield == "last_name") {
if (strlen($value) < 1) {
echo "<p style=\"color:red\">Error: Must be 1+ letters</p>";
} else {
echo "<p style=\"color:green\">Valid</p>";
$_SESSION['reg']['last_name'] = $value;
}
}
// Check Valid or Invalid password when user enters password in password input field.
if ($formfield == "password1") {
if (strlen($value) < 8) {
echo "<p style=\"color:red\">Error: Password too short. Must be at least 8 characters long, contain one lower case letter, one uppercase letter, and one number.</p>";
}
else if (!preg_match("#.*^(?=.{8,20})(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9]).*$#", $value)){
echo "<p style=\"color:red\">Error: Your password must be at least 8 characters long, contain one lower case letter, one uppercase letter, and one number.</p>";
}
else {
echo "<p style=\"color:green\">Your password is good.</p>";
$_SESSION['reg']['password1'] = $value;
}
}
if ($formfield == "password2") {
if (strlen($value) < 8) {
echo "<p style=\"color:red\">Error: Password too short. Must be at least 8 characters long, contain one lower case letter, one uppercase letter, and one number.</p>";
}
else if (!preg_match("#.*^(?=.{8,20})(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9]).*$#", $value)){
echo "<p style=\"color:red\">Error: Your password must be at least 8 characters long, contain one lower case letter, one uppercase letter, and one number.</p>";
}
else if ($_SESSION['password1'] != $value) {
echo "<p style=\"color:red\">Error: Your passwords don't match.</p>";
}
else {
echo "<p style=\"color:green\">Your password is good.</p>";
}
}
// Check Valid or Invalid email when user enters email in email input field.
if ($formfield == "email1") {
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/", $value)) {
echo "<p style=\"color:red\">Invalid email.</p>";
} else {
echo "<p style=\"color:red\">Valid</p>";
$_SESSION['reg']['email1'] = $value;
}
}
?>
And this is my javascript file with the ajax:
function checkForm() {
// Fetching values from all input fields and storing them in variables.
var first_name = document.getElementById("first_name").value;
var last_name = document.getElementById("last_name").value;
var password1 = document.getElementById("password1").value;
var password2 = document.getElementById("password2").value;
var email = document.getElementById("email1").value;
//Check input Fields Should not be blanks.
if (first_name == '' || last_name == '' || password1 == '' || password2 == '' || email1 == '') {
alert("Fill All Fields");
} else {
//Notifying error fields
var textFirstName = document.getElementById("first_name");
var textLastName = document.getElementById("last_name");
var textPass1 = document.getElementById("password1");
var textPass2 = document.getElementById("password2");
var textEmail = document.getElementById("email1");
//Check All Values/Informations Filled by User are Valid Or Not.If All Fields Are invalid Then Generate alert.
str1 = textFirstName.innerHTML; str2 = textLastName.innerHTML; str3 = textPass1.innerHTML; str4 = textPass2.innerHTML; str5 = textEmail.innerHTML;
if (str1.substr(0,4) == 'Error' || str2.substr(0,4) == 'Error' || str3.substr(0,4) == 'Error' || str4.substr(0,4) == 'Error' || str5.substr(0,4) == 'Error') {
alert("Fill Valid Information");
} else {
//Submit Form When All values are valid.
document.getElementById("myForm").submit();
}
}
}
// AJAX code to check input field values when onblur event triggerd.
function validate(field, query) {
var xmlhttp;
if (window.XMLHttpRequest) { // for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else { // for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState != 4 && xmlhttp.status == 200) {
document.getElementById(field).innerHTML = "Validating..";
} else if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById(field).innerHTML = xmlhttp.responseText;
} else {
document.getElementById(field).innerHTML = "Error Occurred. <a href='index.php'>Reload Or Try Again</a> the page.";
}
}
xmlhttp.open("POST", "lib/validate_registration_form.php?field=" + field + "&query=" + query, false);
xmlhttp.send();
}
When I enter values in the form there is no response regardless of whether i input valid or invalid information. I am sure the problem lies in the JS file with the ajax, but I don't know what it is. Any help would be greatly appreciated.
You have two issue :
First, in your html/javascript the onblur event calls
validate('first_name', this.value)
But there is not HTML element with ID = first_name, your div is called textFirstName
So you should change your onblur with proper parameter value such as
validate('textFirstName', this.value)
Next, you use POST method for your ajax but send your parameter in the URL which are stored in the $_GET array
Change :
<?php
$value = $_POST['query'];
$formfield = $_POST['field'];
To :
<?php
$value = $_GET['query'];
$formfield = $_GET['field'];
Final note : you may want to use isset($_GET['query']) in your php script to avoid notice message of undefined or at least a way to debug :
if (!isset($_GET['query']))
{
die ("missing parameter, report to admin that he should debug the JS");
}
EDIT
Following your comment, here is how to send POST data
var params = "field=" + field + "&query=" + query;
xmlhttp.open("POST", "lib/validate_registration_form.php", false);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
//xmlhttp.setRequestHeader("Content-length", params.length);
xmlhttp.send(params);

Add validation to PHP form in responsive HTML

How to I add validation to this php form so that it verifies that a valid email was input and if not post an error message below the input area. I also need it to make sure that all the fields are filled out and that there is no malicious code entered.
Can anyone please help? Thank you in advance.
<?php
$name = $_POST['fullname'];
$email = $_POST['email'];
$message = $_POST['message'];
$subjectCustomer = $_POST['subject'];
$from = 'Contact Form';
$to = 'test#gmail.com';
$subject = "Message from Contact Form: $subjectCustomer";
$location = "http://www.domain.com";
$body = "From: $name\n E-Mail: $email\n Message: $message\n";
## SEND MESSGAE ##
if ($_POST['submit']) {
if ($message != '' && $email != '' && $subject != '') {
if (mail ($to, $subject, $body, $from)) {
echo '<script type="text/javascript">alert("Your message has been sent!"); location.href="index.html";</script>';
} else {
echo '<script type="text/javascript">alert("Something went wrong, go back and try again!"); location.href="index.html/#76industries_contact";</script>';
}
} else {
echo '<script type="text/javascript">alert("You need to fill in all required fields!!"); location.href="index.html/#76industries_contact";</script>';
}
}
?>
<form role="form" method="post" action="contact_form.php" >
<div class="col-md-3">
<div class="form-group">
<input name="fullname" type="text" class="form-control" id="fullname" placeholder="Your Name" maxlength="30">
</div> <!-- end form-group -->
<div class="form-group">
<input name="email" type="text" class="form-control" id="email" placeholder="Your Email" maxlength="30">
</div> <!-- end form-group -->
<div class="form-group">
<input name="subject" type="text" class="form-control" id="subject" placeholder="Your Subject" maxlength="40">
</div> <!-- end form-group -->
<div>
<input id="submit" name="submit" type="submit" value="Send Message" class="btn btn-primary">
</div> <!-- end button -->
</div> <!-- end col-md-3 -->
<div class="form-group">
<div class="col-md-9">
<div class="txtarea">
<textarea name="message" rows="10" class="form-control" id="message" placeholder="Your Message"></textarea>
</div> <!-- end txtarea -->
</div> <!-- end col-md-9 -->
<div> <!-- end form-group -->
<div class="form-group">
<div class="col-sm-10 col-sm-offset-2">
<! Will be used to display an alert to the user>
</div><!-- end col-sm-10 -->
</div> <!-- end form-group -->
</div>
</div>
</form>
here is jquery validation for email and name
$('#submit').click(function(){
var uname=$('#fullname').val();
if($('#fullname').val().match('[a-zA-Z]+\\.?')){
$("#nameerr").css("visibility","hidden");
}
else{
$("#nameerr").text("FullName is InValid" ) ;
$("#nameerr").css("visibility","visible");
return false;
}
});
$('#submit').click(function(){
var email=$('#email').val();
if($('#email').val().match('[A-Z0-9a-z._%+-]+#[A-Za-z0-9.-]+\\.[A-Za-z]{2,6}')){
$("#emailerr").css("visibility","hidden");
}
else
{
$("#emailerr").text("Email Address is InValid.");
$("#emailerr").css("visibility","visible");
return false;
}
});
now you can add another div empty div
<div id="nameerr"> </div>
<div id="emailerr"></div>
now give them css :
#nameerr,#emailerr{
color: red;
background-color:#FFB2B2;
visibility : hidden;
font-weight:bold;
font-size: 12px;
box-shadow: 0 0 5px rgba(255, 0, 0, 1);
width: 150%;
height:10%;
}
As mentioned above in the comments, you can use many ways to achieve what you want.
You could use PHP or JQuery.
If you would like to use PHP, you most likely will end up doing something like:
$name = htmlspecialchars($_POST['fullname']);
$email = $_POST['email'];
$message = htmlspecialchars($_POST['message']);
$subjectCustomer = htmlspecialchars($_POST['subject']);
This takes all the special html characters in a string and converts them to regular html characters.
You can read more on htmlspecialchars here.
Note: You don't want to do a htmlspecialchars() on email addresses. This will convert the # and make it useless.
To check if all fields are filled in, you can use the required attribute from HTML.
Example:
<input name="fullname" type="text" class="form-control" id="fullname" placeholder="Your Name" maxlength="30" required>
Notice that I've placed the attribute inside the input tags.
If you are only looking to achieve client side validation, then I would strongly recommend the jQuery Validation Plugin, that can be found here: http://jqueryvalidation.org/
You can validate your form, on submit with one line of code $("#yourFormName").validate();
Even though you are validating your form's input on the client side, it is still good practice to first check that your variable has some information, then to sanitize your data server side, using a method such as:
if(isset($_POST['fullname'])) {
$name = addslashes($_POST['fullname']
}

Form to different recipients based on radio button input

I cant think anymore, stuck trying to make this work. I've got two radio buttons, how do I send the form to one of two email adresses depending on the button clicked. I am a total idiot on php, thank you.
html
<div class="col-md-8 contact-top">
<h3>Book here Online!</h3>
<form method="post" action="FormtoEmail/FormtoEmail.php">
<form role="form">
<div class="form-group">
<label for="name">Name:</label>
<input type="name" class="form-control" id="name" placeholder="Name">
</div> <div class="form-group">
<label for="email">Email address:</label>
<input type="email" class="form-control" id="email" placeholder="Email">
</div>
<div class="form-group">
<label for="subject">Subject:</label>
<input type="subject" class="form-control" id="subject" placeholder="Subject">
</div>
<div class="radio">
<label><input type="radio" name="recipients" value="recipient_1">Booking Accommodation</label>
</div>
<div class="radio">
<label><input type="radio" name="recipients" value="recipient_2" >Booking Conference</label>
</div>
<div class="form-group">
<textarea rows="11" name="message" id="message" class="form-control" placeholder="Details"></textarea>
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
</div>
my php
<?php
$my_email = "info#westcoastwebdesign.biz";
$continue = "/";
$errors = array();
// Remove $_COOKIE elements from $_REQUEST.
if(count($_COOKIE)){foreach(array_keys($_COOKIE) as $value){unset($_REQUEST[$value]);}}
// Check all fields for an email header.
function recursive_array_check_header($element_value)
{
global $set;
if(!is_array($element_value)){if(preg_match("/(%0A|%0D|\n+|\r+)(content-type:|to:|cc:|bcc:)/i",$element_value)){$set = 1;}}
else
{
foreach($element_value as $value){if($set){break;} recursive_array_check_header($value);}
}
}
recursive_array_check_header($_REQUEST);
if($set){$errors[] = "You cannot send an email header";}
unset($set);
// Validate email field.
if(isset($_REQUEST['email']) && !empty($_REQUEST['email']))
{
if(preg_match("/(%0A|%0D|\n+|\r+|:)/i",$_REQUEST['email'])){$errors[] = "Email address may not contain a new line or a colon";}
$_REQUEST['email'] = trim($_REQUEST['email']);
if(substr_count($_REQUEST['email'],"#") != 1 || stristr($_REQUEST['email']," ")){$errors[] = "Email address is invalid";}else{$exploded_email = explode("#",$_REQUEST['email']);if(empty($exploded_email[0]) || strlen($exploded_email[0]) > 64 || empty($exploded_email[1])){$errors[] = "Email address is invalid";}else{if(substr_count($exploded_email[1],".") == 0){$errors[] = "Email address is invalid";}else{$exploded_domain = explode(".",$exploded_email[1]);if(in_array("",$exploded_domain)){$errors[] = "Email address is invalid";}else{foreach($exploded_domain as $value){if(strlen($value) > 63 || !preg_match('/^[a-z0-9-]+$/i',$value)){$errors[] = "Email address is invalid"; break;}}}}}}
}
// Check referrer is from same site.
if(!(isset($_SERVER['HTTP_REFERER']) && !empty($_SERVER['HTTP_REFERER']) && stristr($_SERVER['HTTP_REFERER'],$_SERVER['HTTP_HOST']))){$errors[] = "You must enable referrer logging to use the form";}
// Check for a blank form.
function recursive_array_check_blank($element_value)
{
global $set;
if(!is_array($element_value)){if(!empty($element_value)){$set = 1;}}
else
{
foreach($element_value as $value){if($set){break;} recursive_array_check_blank($value);}
}
}
recursive_array_check_blank($_REQUEST);
if(!$set){$errors[] = "You cannot send a blank form";}
unset($set);
// Display any errors and exit if errors exist.
if(count($errors)){foreach($errors as $value){print "$value<br>";} exit;}
if(!defined("PHP_EOL")){define("PHP_EOL", strtoupper(substr(PHP_OS,0,3) == "WIN") ? "\r\n" : "\n");}
// Build message.
function build_message($request_input){if(!isset($message_output)){$message_output ="";}if(!is_array($request_input)){$message_output = $request_input;}else{foreach($request_input as $key => $value){if(!empty($value)){if(!is_numeric($key)){$message_output .= str_replace("_"," ",ucfirst($key)).": ".build_message($value).PHP_EOL.PHP_EOL;}else{$message_output .= build_message($value).", ";}}}}return rtrim($message_output,", ");}
$message = build_message($_REQUEST);
$message = $message . PHP_EOL.PHP_EOL."-- ".PHP_EOL."";
$message = stripslashes($message);
$subject = "Out of Africa Town Lodge Contact Form";
$headers = "From: " . $_POST['email'];
$recipients = array(
'recipient_1' => 'info#westcoastwebdesign.biz',
'recipient_2' => 'westcoastwebdesign77#gmail.com'
);
$my_email = $recipients[$_REQUEST['recipient']];
mail($my_email,$subject,$message,$headers);
?>
You need to use a radio button group with same name but value with different email id
<div class="radio">
<label><input type="radio" name="recipients" value="recipient_1#email.com">
Booking Accommodation
</label>
</div>
<div class="radio">
<label><input type="radio" name="recipients" value="recipient_2#email.com" >
Booking Conference
</label>
</div>
That way you can select one from two radio
in FormtoEmail.php
//use post to get the email id
$to = $_POST['recipients'];
and send mail using PHPMailer, its great library and will make your life easier
May you want use this code:
<?php
if(isset($_POST['recipients']) && $_POST['recipients'] == 'recipient_1') {
// send to recipient_1
} else {
// send to recipient_2
}
?>
$my_email = $recipients[$_REQUEST['recipient']];
There is a typo in $_REQUEST variable, it would be $recipients[$_REQUEST['recipients']];
Hope it will work now. It could be more easily done in anyway.

Categories

Resources