Form to different recipients based on radio button input - javascript

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.

Related

Html form refuses to be submitted via JQuery

So I was following an AJAX/JQuery tutorial for a registration script that will be acted upon by PHP/MySQL and will be submitted via JQuery.
Now the problem that I'm encountering is that the form submits directly to the action page, which should not be so, as it supposed to submit to script.js Here are the html code for the form.
<form method="post" id="register-form" action="transact-user.php">
<h2 class="form-signin-heading"></h2>
<div class="form-group">
<div class='row'>
<div class='col-sm-6'>
<input type='text' class='form-control' id='fname' name='fname' placeholder="First name">
</div>
<div class='col-sm-6'>
<input type='text' class='form-control' id='lname' name='lname' placeholder="Last name">
</div>
</div>
</div>
<div class="form-group">
<input type="text" class="form-control" placeholder="Phone Number" name = "phone" id = "phone" >
</div>
<div class="form-group">
<input type="email" class="form-control" placeholder="Email address" name = "email" id ="email">
<span id="check-e"></span>
</div>
<div class="form-group">
<input type="password" class="form-control" placeholder="Password" name = "password" id = "password">
</div>
<div class="form-group">
<input type="password" class="form-control" placeholder="Password Again" name = "confirmpassword" id = "confirmpassword">
</div>
<div class="form-group">
<button class="btn btn-primary btn-block btn-apply" type="submit" name="btn-save" id = "btn-submit"><span class="glyphicon glyphicon-log-in"></span> Register</button>
</div>
</form>
</div> <!-- /container -->
<div id = "ack"></div>
script.js
$("button#btn-submit").click(function()
{ /* validation */
/* form submit */
if ($("fname").val()=="" || $("lname").val()=="" )
$("div#ack").html("Please enter both your first name and your surname");
else
$.post($("#register-form").attr("action"),
$("#register-form: input").serializeArray(),
function(data){
$("div#ack").html(data);
});
$("#register-form").submit(function(){
return false;
})
/* form submit */
});
Finally, this is the action php script transact-user.php
<?php
if($_POST)
{
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$password = $_POST['password'];
$confirmpassword = $_POST['confirmpassword'];
if($email != '') {
$qry = "SELECT * FROM users WHERE email='$email'";
$result = mysqli_query($mysqli,$qry);
if($result) {
if(mysqli_num_rows($result) > 0) {
echo "Email already in use";
}
#mysqli_free_result($result);
}
else {
die("Query failed");
}
}
$activation = md5(uniqid(rand(), true));
if ($stmt = "INSERT INTO users(firstname, lastname, email, password, verification, phone)"
." values('$fname', '$lname', '$email', '$password', "
. "'$activation','$phone')" or
die("Could not perform query ".mysqli_error($mysqli))) {
$result = mysqli_query($mysqli, $stmt)
or die("The system could not register you"
. "".mysqli_error($mysqli) . "<br>" . $stmt);
if ($result){
echo "sent";
}
//echo "<a href=\"gethotel.php?hid=".$row['hotel_id'].
//
/* close statement */
//$stmt->close();
}
}
?>
The issue us because you are hooking to the click event of the submit button and are not preventing the event from completing.
Also note that your selector to build the querystring is incorrect, as there should be a space before the : and not between the : and input, eg $("#register-form :input")
To fix the issues hook to the submit event of the form and use preventDefault(). Try this:
$("#register-form").submit(function(e) {
e.preventDefault();
if ($("fname").val().trim() == "" || $("lname").val().trim() == "") {
$("div#ack").html("Please enter both your first name and your surname");
} else {
$.post(this.action, $(this).find(':input').serializeArray(), function(data) {
$("div#ack").html(data);
});
}
});

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']
}

Contact form - cannot get email to send

I am trying to create a basic form to send an email and here is how it looks:
http://www.unitedserbians.com/contact_us.html
I have everything working and buttoned up, except I cannot get the actual email to be sent once the form has completed processing. My function executes as my field validations work great and I can see the correct values are being grabbed from the form by un-commenting the JAVA script code "alert (dataString);return false;" and even the .ajax executes because I get "Contact Form Sent! We will be in touch soon." message displayed but the actual email never gets sent. I am guessing that something is missing in the process.php file. I cannot trace to see where the issue occurs or if my process.php ever executes. Should the file live in the same directory with JAVA script? or at main directory bin folder? Or is there something I am blindly missing in the process code? Can someone spot what am I missing please? Much appreciated in advance.
HTML:
<div class="content">
<div class="content_resize">
<div class="mainbar">
<div class="article">
<h2><span>Send us E-Mail</span></h2>
<div id="contact_form">
<form action="" form name="contact">
<fieldset>
<ol>
<li>
<label for="name" id="name_label">Your Full Name</label>
<input type="text" name="name" id="name" size="30" value="" class="text-input" />
<label2 class="error" for="name" id="name_error">This field is required.</label2>
</li>
<li>
<label for="email" id="email_label">Your Email Address</label>
<input type="text" name="email" id="email" size="30" value="" class="text-input" />
<label2 class="error" for="email" id="email_error">This field is required.</label2>
</li>
<li>
<label for="website id="phone_label">Your Phone Number</label>
<input type="text" name="phone" id="phone" size="30" value="" class="text-input" />
<label2 class="error" for="phone" id="phone_error">This field is required.</label2>
</li>
<li>
<label for="message">Your Message</label>
<textarea id="message" name="message" rows="8" cols="50"></textarea>
</li>
<li>
<input type="submit" name="imageField" id="submit_btn" src="images/submit.gif" class="send" />
</li>
</ol>
</fieldset>
</form>
</div>
</div>
</div>
JAVA script:
$(function() {
$('.error').hide();
$(".send").click(function() {
// validate and process form here
$('.error').hide();
var name = $("input#name").val();
if (name == "") {
$("label2#name_error").show();
$("input#name").focus();
return false;
}
var email = $("input#email").val();
if (email == "") {
$("label2#email_error").show();
$("input#email").focus();
return false;
}
var phone = $("input#phone").val();
if (phone == "") {
$("label2#phone_error").show();
$("input#phone").focus();
return false;
}
var message = $("textarea#message").val();
var dataString = 'name='+ name + '&email=' + email + '&phone=' + phone + '&message=' + message;
// alert (dataString);
// return false;
$.ajax({
type: "POST",
url: "bin/process.php",
data: dataString,
success: function() {
$('#contact_form').html("<div id='send_message'></div>");
$('#send_message').html("<h2>Contact Form Sent!</h2>")
.append("<p>We will be in touch soon.</p>");
}
});
return false;
});
});
PHP:
<?php
$email_to = "XXXXX#gmail.com";
$email_subject = "Message sent using contact form.";
$name = $_POST['name']; // required
$email_from = $_POST['email']; // required
$phone = $_POST['phone']; // required
$message = $_POST['message'];
$email_message .= "Full Name: ".clean_string($name)."\n";
$email_message .= "Email: ".clean_string($email_from)."\n";
$email_message .= "Phone Number: ".clean_string($phone)."\n";
$email_message .= "Message: ".clean_string($message)."\n";
// create email headers
$headers = 'From: '.$email_from."\r\n".
'Reply-To: '.$email_from."\r\n" .
'X-Mailer: PHP/' . phpversion();
#mail($email_to, $email_subject, $email_message, $headers);
?>
One possibility is that your host doesn't like the $email_from address. I think most hosts are restrictive about sending using a From address that isn't associated with that host (this is so to not enable spammers). Try using no-reply#yourdomain.com or something like that, or even better an address that really exists, as your From address. The Reply-To can still be the address the user enters (after you check that it is valid).

How to return to the previous page after a submit form with php?

I have a form in html whose "action" attribute calls a contact.php file. The problem is that after I submit the form, the file that is visible is a blank page with the address contact.php and I want to see again the form of the main page.
HTML:
<form id="myForm" action="php-contact/contact.php"
method="post" class="contact_form" autocomplete="off"
role="form">
<div class="form-group">
<label for="input-subject">subject</label>
<input name="subject" type="text" class="form-control" id="subject" placeholder="your subject" maxlength="20"/>
</div>
<div class="form-group">
<label for="input-name">name</label>
<input name="name" type="text" class="form-control" id="name" placeholder="your name" maxlength="20"/>
</div>
<div class="form-group">
<label for="input-email">email address</label>
<input name="email" type="text" class="form-control" id="email" placeholder="your email" maxlength="40"/>
</div>
<div class="form-group" >
<label for="input-message">message</label>
<textarea name="message" cols="10" rows="10" class="form-control" id="comment" ></textarea>
</div>
<button name="myFormSubmitted" type="submit" class="btn btn-primary btn-lg btn-block">send</button>
</form>
PHP:
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$message = $_POST['message'];
$to = "pep.g#gmail.com";
$message = '
name: '.$name.'
email: '.$email.'
message: '.$message.'
';
$headers = 'From: pep.website#website.com';
if (
mail($to, $subject, $message, $headers)
)
echo"<script>alert('message send succesfully')</script>";
else
echo"<script>alert('message not send')</script>";
?>
Use either $_SERVER["HTTP_REFERER"] or use a hidden field on the form with the url of the current page:
<form action="myAction.php">
<input type="hidden" name="destination" value="<?php echo $_SERVER["REQUEST_URI"]; ?>"/>
<!-- other form inputs -->
<input type="submit"/>
</form>
myAction.php
<?php
/* Do work */
if(isset($_REQUEST["destination"])){
header("Location: {$_REQUEST["destination"]}");
}else if(isset($_SERVER["HTTP_REFERER"])){
header("Location: {$_SERVER["HTTP_REFERER"]}");
}else{
/* some fallback, maybe redirect to index.php */
}
And then even then you should have fallbacks in case for some reason the client isn't respecting HTTP redirects, like some redirect javascript, a meta redirect and a link to the destination.
Add a JS redirect after your alert then
echo "<script>
alert('message sent succesfully');
window.history.go(-1);
</script>";
In your contact.php file, just use something like at the end of the PHP code:
header("location:yourfilenamehere.php");
This will redirect back to whatever page you specify.
You could do two things...
1) Have your php logic in the form file and submit to that file. On the top of the file, put something like:
if(isset($_POST['name'])) {
// your sending logic
}
followed by your form.
2) use the header() function to redirect to your form.
header("Location: form.html");
I feel pretty bad about posting this answer as it is just concatenating two other SO answers.
First part
Charlie74's answer on this page
// add the message you want to show to the user
header("Location: yourfilenamehere.php?alertmsg=message+send+succesfully");
exit();
Second part check for the alertmsg name in the query string
See SO post for getParameterByName:
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
in the page you are redirecting call the getParameterByName function:
<script>
var msg = getParameterByName('alertmsg');
if (alertmsg.length > 0) {
alert(msg);
}
</script>

Can I remove "&& isset" in a php form

I have got the following form to work using PHP and JavaScript to validate...
The problem is, each time I want to update the inputs in the form I need to also update the && isset and $input = $_REQUEST['input name']; in the PHP! Are these important? there is no way to make the whole process easier?! please advise
PHP:
<?php
session_start();
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
ob_start();
if(isset($_REQUEST['name'])
&& isset($_REQUEST['email'])
&& isset($_REQUEST['message'])
&& isset($_REQUEST['number'])
&& isset($_REQUEST['date'])
&& isset($_REQUEST['select'])
&& isset($_REQUEST['radio'])
&& isset($_REQUEST['checkbox'])
&& isset($_REQUEST['token'])){
if($_SESSION['token'] != $_POST['token']){
$response = "0";
} else {
$_SESSION['token'] = "";
$name = $_REQUEST['name'];
$email = $_REQUEST['email'];
$message = $_REQUEST['message'];
$number = $_REQUEST['number'];
$date = $_REQUEST['date'];
$select = $_REQUEST['select'];
$radio = $_REQUEST['radio'];
$checkbox = $_REQUEST['checkbox'];
$to = "";
$subject = "New Message From: $name";
$message = "Name: $name<br/>
number: $number<br/>
date: $date<br/>
select: $select<br/>
radio: $radio<br/>
checkbox: $checkbox<br/>
Email: $email<br/>
Message: $message";
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=utf-8' . "\r\n";
$headers .= 'From: '.$email . "\r\n";
$mailed = (mail($to, $subject, $message, $headers));
if( isset($_REQUEST['ajax']))$response = ($mailed) ? "1" :
"0"; else $response = ($mailed) ? "<h2>Success!</h2>" :
"<h2>Error! There was a problem with sending.</h2>";
echo $response;
}
} else {
echo "Form data error!";
}
ob_flush();
die();
}
?>
HTML Form:
<?php
$token = md5(uniqid(rand(), TRUE));
$_SESSION['token'] = $token;
?>
<!--Contact Form-->
<form id="contactForm" name="contactForm" action="contact.php" method="post">
<input name="token" type="hidden" value="<?php echo $token; ?>">
<input name="ajax" type="hidden" value="1">
<div class="name">
<p>Your Name</p>
<input name="name" class="required" autocomplete="off">
</div>
<div class="email-address">
<p>Email Address</p>
<input name="email" class="required email" autocomplete="off">
</div>
<div class="message">
<p>Message</p>
<textarea name="message" rows="5" class="required min3"></textarea>
</div>
<div class="number">
<p>Phone Number</p>
<input name="number" class="number" autocomplete="off">
</div>
<div class="date">
<p>Date <small>(dd/mm/yyyy)</small></p>
<input name="date" class="required date calendar" autocomplete="off">
</div>
<div class="dropdown">
<select name="select" class="required">
<option value="">Select</option>
<option value="DropdownA">DropdownA</option>
<option value="DropdownB">DropdownB</option>
</select>
</div>
<div class="radio">
<p>Radios:</p>
<label><input name="radio" type="radio" value="male" class="required">Male</label>
<label><input name="radio" type="radio" value="female" class="required">Female</label>
</div>
<div class="checkbox">
<p>Checkboxs:</p>
<label><input name="checkbox" type="checkbox" value="OptionA" class="required">Option A</label>
<label><input name="checkbox" type="checkbox" value="OptionB" class="required">Option B</label>
</div>
<div>
<p></p>
<input name="" class="required number spamcheck">
</div>
<button id="submit" type="submit">Send</button>
</form>
You do need to check if variables are set, before using them. Otherwise your script will raise errors for undefined variables. E.g. You each time will try to check if $_SESSION['token'] != $_POST['token'] but it will give you errors, because there's no form submitted (or however the request is sent) with token name, that's why you do need to check it before that.
Anyway, for multiple isset() you can use a comma separator
if(isset($var, $var2, $var3...))
instead of
if(isset($var) && isset($var2)...))
Also,, if you session token is not initialized too (completely new request to the page), and no request is send to it, your if() statement will return false, thus triggering the mail() function. So, in you particular case it's more than necessary to have a check before using them in mail form.
Yes. They are important. Lots of ways to make the process easier though. You might want to look at a simple framework like Symfony (the forms component can be used independently of the whole framework).
Be aware that you'll probably get a massive amount of spam with that form. Add a captcha like reCaptcha.
Yes, the validation is important but you can simplify your code. I would use an array to define the required fields. It's easy to maintain and much less code.
$requiredFields = array('name', 'email', 'message', 'number');
$valid = true;
foreach ($requiredFields as $field) {
if (!isset($_REQUEST[$field])) {
$valid = false;
break;
}
}
if ($valid) {
// Do the stuff
} else {
echo "Form data error!";
}
If you want to check if the current field actually contains something add empty() to the condition:
if (!isset($_REQUEST[$field]) || empty($_REQUEST[$field])) {
I think the second part where you assign the post values to separate variables is actually unnecessary in this case.

Categories

Resources