Checkbox Validation and Post PHP, quick one :) - php

I need to check that the check box is checked (required) and need the validation to perform much like the other form fields, and then i need to post the value in email.
PHP for entire form as it stands:
<?php
if(isset($_POST['formtrigger'])):
//config
define('FORM_SENDTO','hello#domain.com');
define('FORM_SUBJECTLINE','Enquiry from website');
define('ERR_MSG_FIELD_REQUIRED','This field is required.');
define('ERR_MSG_FIELD_INVALIDEMAIL','Please enter a valid email address.');
//setup validation rules
//Name
$validation_rules['forename']['required'] = true;
$validation_rules['surname']['required'] = true;
//Company
$validation_rules['company']['required'] = true;
//Address
$validation_rules['address']['required'] = true;
//Tel
$validation_rules['tel']['required'] = true;
//Email
$validation_rules['email']['required'] = true;
$validation_rules['email']['valid_email'] = true;
//Enquiry
$validation_rules['enquiry']['required'] = true;
//title/gender
$validation_rules['ts1']['required'] = true;
$validation_rules['ts2']['required'] = true;
//validate the form
$formerrors=0;
foreach($_POST as $formfield_name=>$formfield_value):
//set the entered value as a sanitised string
$_POST_SANITISED[$formfield_name] = filter_var($formfield_value,FILTER_SANITIZE_STRING);
//Check if required
if($validation_rules[$formfield_name]['required']):
if(!strlen($formfield_value)>0):
$formerrors++;
$fielderrors[$formfield_name][] = ERR_MSG_FIELD_REQUIRED;
endif;
endif;
//Check if valid email required
if($validation_rules[$formfield_name]['valid_email']):
if(!filter_var($formfield_value,FILTER_VALIDATE_EMAIL)):
$formerrors++;
$fielderrors[$formfield_name][] = ERR_MSG_FIELD_INVALIDEMAIL;
endif;
endif;
endforeach;
//process form and send message if validation passed
if($formerrors==0):
$email_msg[] = "New general enquiry\n\n-----------\n";
$email_msg[] = "Title: ".$_POST_SANITISED['ts1']."\n";
$email_msg[] = "Gender: ".$_POST_SANITISED['ts2']."\n";
$email_msg[] = "Forename: ".$_POST_SANITISED['forename']."\n";
$email_msg[] = "Surname: ".$_POST_SANITISED['surname']."\n";
$email_msg[] = "Company: ".$_POST_SANITISED['company']."\n";
$email_msg[] = "Address: ".$_POST_SANITISED['address']."\n";
$email_msg[] = "Telephone No.: ".$_POST_SANITISED['tel']."\n";
$email_msg[] = "Email: ".$_POST_SANITISED['email']."\n";
$email_msg[] = "Enquiry: ".$_POST_SANITISED['enquiry']."\n";
$email_msg[] = "-----------\n";
$email_msg = implode('',$email_msg);
$email_headers = 'From: ' . $_POST_SANITISED['email'] . "\r\n" .
'Reply-To: ' . $_POST_SANITISED['email'] . "\r\n" .
'X-Mailer: PHP/' . phpversion();
mail(FORM_SENDTO,FORM_SUBJECTLINE,$email_msg,$email_headers);
header('Location: ?msgsent=1#thanks');
endif;
endif;
function errorOutput($fieldname=''){
global $fielderrors;
if(count($fielderrors[$fieldname])>0):
foreach($fielderrors[$fieldname] as $err_msg):
$error_str .= '<div class="form-fielderror-msg">'.$err_msg.'</div>';
endforeach;
endif;
return $error_str ? $error_str : false;
}
function errorClass($fieldname=''){
global $fielderrors;
$error_class = '';
if(count($fielderrors[$fieldname])>0):
$error_class = 'form-fielderror';
endif;
return $error_class ? $error_class : false;
}
?>
Here is the HTML:
<?php if($_GET['msgsent']==1): ?>
<h1>Thanks for your enquiry. If requested, we will get in touch shortly.</h1>
<?php else: ?>
<div id="form-cont">
<form action="<?=$_SERVER['PHP_SELF']?>" method="post">
<div class="form-element">
<label for="ts1">Title:*</label>
<select name="ts1" class="<?=errorClass('ts1')?>">
<option value="">-- Please select --</option>
<option value="Mr" <?=$_POST['ts1']=='Mr' ? 'selected="selected"' : '' ?>>Mr</option>
<option value="Mrs" <?=$_POST['ts1']=='Mrs' ? 'selected="selected"' : '' ?>>Mrs</option>
<option value="Miss" <?=$_POST['ts1']=='Miss' ? 'selected="selected"' : '' ?>>Miss</option>
<option value="Ms" <?=$_POST['ts1']=='Ms' ? 'selected="selected"' : '' ?>>Ms</option>
</select>
<?=errorOutput('ts1')?>
</div>
<div class="form-element">
<label for="ts2">Gender:*</label>
<select name="ts2" class="<?=errorClass('ts2')?>">
<option value="">-- Please select --</option>
<option value="Male" <?=$_POST['ts2']=='Male' ? 'selected="selected"' : '' ?>>Male</option>
<option value="Female" <?=$_POST['ts2']=='Female' ? 'selected="selected"' : '' ?>>Female</option>
</select>
<?=errorOutput('ts2')?>
</div>
<div class="form-element">
<label for="forename">Forename:*</label>
<input type="text" name="forename" class="textbox <?=errorClass('forename')?>" value="<?=$_POST['forename']?>" />
<?=errorOutput('forename')?>
</div>
<div class="form-element">
<label for="surname">Surname:*</label>
<input type="text" name="surname" class="textbox <?=errorClass('surname')?>" value="<?=$_POST['surname']?>" />
<?=errorOutput('surname')?>
</div>
<div class="form-element">
<label for="company">Company:*</label>
<input type="text" name="company" class="textbox <?=errorClass('company')?>" value="<?=$_POST['company']?>" />
<?=errorOutput('company')?>
</div>
<div class="form-element">
<label for="address">Address:*</label>
<input type="text" name="address" class="textbox <?=errorClass('address')?>" value="<?=$_POST['address']?>" />
<?=errorOutput('address')?>
</div>
<div class="form-element">
<label for="tel">Telephone No:*</label>
<input type="text" name="tel" class="textbox <?=errorClass('tel')?>" value="<?=$_POST['tel']?>" />
<?=errorOutput('tel')?>
</div>
<div class="form-element">
<label for="email">Email:*</label>
<input type="text" name="email" class="textbox <?=errorClass('email')?>" value="<?=$_POST['email']?>" />
<?=errorOutput('email')?>
</div>
<div class="form-element">
<label for="enquiry">Your Enquiry:*</label>
<textarea name="enquiry" class="<?=errorClass('enquiry')?>"><?=$_POST['enquiry']?></textarea>
<?=errorOutput('enquiry')?>
</div>
<div class="form-element">
<label for="terms">Terms and Conditions</label>
<input type="checkbox" name="terms" class="checkbox <?=errorClass('terms')?>" value="<?=$_POST['terms']=1?>" />
<?=errorOutput('terms')?>
</div>
<div class="form-element">
<p class="clear">* denotes required field.</p>
<input type="submit" class="submit" name="submit" value="Send" alt="Submit" title="Submit" />
</div>
<input type="hidden" name="formtrigger" value="1" />
</form>
</div>
<?php endif ?>
The checkbox in question as at the bottom:
<div class="form-element">
<label for="terms">Terms and Conditions</label>
<input type="checkbox" name="terms" class="checkbox <?=errorClass('terms')?>" value="<?=$_POST['terms']=1?>" />
<?=errorOutput('terms')?>
</div>
Many thanks for you help! :)

if (isset($_POST['terms']))
{
// checked
}

There is no way in the world this code would run validations of check box is the least of your problem
A. You have so many Notice: Undefined index errors like 55
B. This would not work expect your server supports short tags ''
C. Too Many duplication
I would only correct the error of validation you requested but trust me so many things are wrong
$formerrors=0;
$_POST_SANITISED = array();
foreach($_POST as $formfield_name=>$formfield_value){
//set the entered value as a sanitised string
$_POST_SANITISED[$formfield_name] = filter_var($formfield_value,FILTER_SANITIZE_STRING);
//Check if required
if(isset($validation_rules[$formfield_name]['required']))
{
if(!strlen($formfield_value)>0){
$formerrors++;
$fielderrors[$formfield_name][] = ERR_MSG_FIELD_REQUIRED;
}
}
//Check if valid email required
if(isset($validation_rules[$formfield_name]['valid_email']))
{
if(!filter_var($formfield_value,FILTER_VALIDATE_EMAIL)){
$formerrors++;
$fielderrors[$formfield_name][] = ERR_MSG_FIELD_INVALIDEMAIL;
}
}
};
if(!isset($_POST['terms']))
{
$formerrors++;
$fielderrors["terms"][] = ERR_MSG_FIELD_REQUIRED;
}

Related

After submiting a php form I get empty window and no e-mail

Update:
I've added echo $errors to the end of my code. Now I am getting that all fields are required although all are filled:
} else {
echo $errors;
}
I've created a simple php e-mail form with this example (link). And jQuery form validator (link).
Now what I get after submiting a form is just a empty "contact-form-handler.php" page.
You can see the form live at: mantasmilka.com/#contactPage
What could be the problem? Below is my code.
contact-form-handler.php
<?php
$errors = '';
$myemail = 'mantas#mantasmilka.com';//<-----Put Your email address here.
if(empty($_POST['infoname']) ||
empty($_POST['infocompany']) ||
empty($_POST['infoemail']) ||
empty($_POST['infophone']) ||
empty($_POST['infodescription'])
)
{
$errors .= "\n Error: all fields are required";
}
$jobtype = $_POST['jobtype'];
$budget = $_POST['budget'];
$location = $_POST['location'];
$infoname = $_POST['infoname'];
$infocompany = $_POST['infocompany'];
$infoemail = $_POST['infoemail'];
$infophone = $_POST['infophone'];
if (isset($_POST['infodescription'])) {
$infodescription = $_POST['infodescription'];
}
if (!preg_match(
"/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i",
$infoemail))
{
$errors .= "\n Error: Invalid email address";
}
if( empty($errors))
{
$to = $myemail;
$email_subject = "Contact form submission: $name";
$email_body = "You have received a new message. ".
" Here are the details:\n Jobtype: $jobtype \n Budget: $budget \n Location: $location \n Name: $infoname \n Company: $infocompany \n E-mail: $infoemail \n Phone: $infophone \n ".
"Message \n $infodescription";
$headers = "From: $myemail\n";
$headers .= "Reply-To: $infoemail";
mail($to,$email_subject,$email_body,$headers);
//redirect to the 'thank you' page
// header('Location: http://www.mantasmilka.com/index.php');
header('Location: index.php');
exit();
} else {
echo $errors;
}
?>
my form in index.php:
<form id="contactform" method="post" name="contact_form" action="contact-form-handler.php">
<div class="left">
<fieldset class="jobtype">
<legend>Job type</legend>
<input type="radio" name="jobtype" id="project" value="project" required>
<label for="project">Project</label>
<input type="radio" name="jobtype" id="part-time" value="part-time" >
<label for="part-time">Part-time</label>
<input type="radio" name="jobtype" id="full-time" value="full-time" >
<label for="full-time">Full-time</label>
</fieldset>
<fieldset class="budget">
<legend>Budget</legend>
<input type="radio" name="budget" id="budget5k" value="budget5k" required>
<label for="budget5k">5k € ></label>
<input type="radio" name="budget" id="budget10k" value="budget10k" >
<label for="budget10k">5k - 10k €</label>
<input type="radio" name="budget" id="budget15k" value="budget15k" >
<label for="budget15k">15k € <</label>
</fieldset>
<fieldset class="location">
<legend>Location</legend>
<input type="radio" name="location" id="locremote" value="locremote" required>
<label for="locremote">Remote</label>
<input type="radio" name="location" id="loclocal" value="loclocal" >
<label for="loclocal">Local with relocation</label>
</fieldset>
</div>
<div class="right">
<fieldset class="contactinfo">
<legend>Your Contact Info</legend>
<div class="input-holder">
<input type="text" name="infoname" id="infoname" value="" required data-validation="alphanumeric">
<label for="infoname">Name</label>
</div>
<div class="input-holder">
<input type="text" name="infocompany" id="infocompany" value="" required data-validation="alphanumeric">
<label for="infocompany">Company</label>
</div>
<div class="input-holder">
<input type="text" name="infoemail" id="infoemail" value="" required data-validation="email">
<label for="infoemail">E-mail</label>
</div>
<div class="input-holder">
<input type="text" name="infophone" id="infophone" value="" required data-validation="number">
<label for="infophone">Phone</label>
</div>
<div class="input-holder textarea">
<textarea name="infodescription" form="contact_form" rows="4" required></textarea>
<label for="infodescription">Message</label>
</div>
<div class="input-holder submit">
<input type="submit" name="submit" value="Submit" required/>
</div>
</fieldset>
</div>
</form>
text field should look like this don't put form tag in here
<textarea name="infodescription" rows="4" required></textarea>
in php make the if statement like this the first ( opens the if statement the last ) closes it and take not of how i used the other brackets
if(
(empty($_POST['infoname'])) ||
(empty($_POST['infocompany'])) ||
(empty($_POST['infoemail'])) ||
(empty($_POST['infophone'])) ||
(empty($_POST['infodescription']))
)
{
$errors .= "\n Error: all fields are required";
}
The efficient way to solve the problem is:
$('#contactform').submit(function(ev) {
ev.preventDefault();
if($('#infodescription').val() == '')
{
alert('Description is required');
return false;
}
//add other validation
this.submit(); // If all the validations succeeded
});
By this you can avoid the unwanted server load.

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

PHP is only submitting the last selection of a multi selection drop-down menu

I am a newbie to PHP, and I really don't know what I am doing wrong or even if what I have done is correct, but it seems working, however only the drop-down menus aren't fully working.
The $SelectThree and $SelectFour only shows the last selection... for example if you picked DropDown Option A and B... only B will show in the email... i.e:
Name: name
Number: number
Date: 10/06/2014
Select: DropdownA
Select2: DropdownA
Select3: Drop Down Option B
Select4: Drop Down Option B
Radio: female
Checkbox: OptionB
Switch: On
Email: example#example.com
Message: message
PHP:
<?php
session_start();
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
ob_start();
if(isset(
$_REQUEST['name'],
$_REQUEST['email'],
$_REQUEST['message'],
$_REQUEST['number'],
$_REQUEST['date'],
$_REQUEST['select'],
$_REQUEST['selectTwo'],
$_REQUEST['selectThree'],
$_REQUEST['selectFour'],
$_REQUEST['radio'],
$_REQUEST['checkbox'],
$_REQUEST['switch'],
$_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'];
$selectTwo = $_REQUEST['selectTwo'];
$selectThree = $_REQUEST['selectThree'];
$selectFour = $_REQUEST['selectFour'];
$radio = $_REQUEST['radio'];
$checkbox = $_REQUEST['checkbox'];
$switch = $_REQUEST['switch'];
switch (true){
case !filter_var($email, FILTER_VALIDATE_EMAIL):
$response = "<p style='color:red'>Invalid Email Address!</p>";
break;
default:
$to = "support#loaidesign.co.uk";
$subject = "New Message From: $name";
$message = "Name: $name <br/>
Number: $number <br/>
Date: $date <br/>
Select: $select <br/>
Select2: $selectTwo <br/>
Select3: $selectThree <br/>
Select4: $selectFour <br/>
Radio: $radio <br/>
Checkbox: $checkbox <br/>
Switch: $switch <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: '."support#loaidesign.co.uk" . "\r\n";
$headers .= 'Reply-To: '.$email . "\r\n";
$params = '-f support#loaidesign.co.uk';
$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>";
}
break;
}
echo $response;
}
} else {
echo "Error";
}
ob_flush();
die();
}
?>
Contact form HTML:
<!--Contact Form-->
<?php $token = md5(uniqid(rand(), TRUE)); $_SESSION['token'] = $token;?>
<form id="contactForm" class="validate" name="contactForm" action="contact.php" method="post">
<input name="token" type="hidden" value="<?php echo $token; ?>">
<input name="ajax" type="hidden" value="1">
<fieldset>
<p>Your Name</p>
<input name="name" class="name required fullname" autocomplete="off">
</fieldset>
<fieldset>
<p>Email Address</p>
<input name="email" type="email" class="email required" autocomplete="off">
</fieldset>
<fieldset>
<p>Message</p>
<textarea name="message" rows="5" class="required min3"></textarea>
</fieldset>
<fieldset>
<p>Phone Number</p>
<input name="number" class="hasIcon" autocomplete="off">
<i class="form-icon icon-phone"></i>
</fieldset>
<fieldset>
<p>Time</p>
<input name="time" class="mask-time hasIcon" autocomplete="off">
<i class="form-icon icon-clock"></i>
</fieldset>
<fieldset>
<p>Date</p>
<input name="date" class="required date calendar hasIcon" autocomplete="off">
<i class="form-icon icon-calendar"></i>
</fieldset>
<fieldset>
<p class="inline">Date Selected:</p>
<input class="selectedDate inline"></input>
</fieldset>
<fieldset>
<p>Dropdown Menu</p>
<select name="select" class="select required" data-placeholder="Choose an option">
<option value=""></option>
<option value="DropdownA">DropdownA</option>
<option value="DropdownB">DropdownB</option>
</select>
</fieldset>
<fieldset>
<p>Dropdown Menu - Searchable</p>
<select name="selectTwo" class="select-search" data-placeholder="Choose an option">
<option value=""></option>
<option value="DropdownA">DropdownA</option>
<option value="DropdownB">DropdownB</option>
</select>
</fieldset>
<fieldset>
<p>Multi Options Dropdown Menu</p>
<select name="selectThree" class="select multi-select" multiple="multiple" tabindex="-1" data-placeholder="Choose an option">
<option value=""></option>
<optgroup label="Section One">
<option>Drop Down Option A</option>
<option>Drop Down Option B</option>
</optgroup>
<optgroup label="Section Two">
<option>Drop Down Option A</option>
<option>Drop Down Option B</option>
<option>Drop Down Option C</option>
<option>Drop Down Option D</option>
</optgroup>
</select>
</fieldset>
<fieldset>
<p>Multi Options Dropdown Menu - Min 2 & Max 3</p>
<select name="selectFour" class="select multi-select" multiple="multiple" tabindex="-1" min="2" max="3">
<option value=""></option>
<option>Drop Down Option A</option>
<option>Drop Down Option B</option>
<option>Drop Down Option A</option>
<option>Drop Down Option B</option>
</select>
</fieldset>
<fieldset class="checkbox">
<p>Checkboxs:</p>
<label><input name="checkbox" type="checkbox" value="OptionA" class="required"><span class="checked-icon"><span></span></span><span>Option A</span></label>
<label><input name="checkbox" type="checkbox" value="OptionB" class="required"><span class="checked-icon"><span></span></span><span>Option B</span></label>
</fieldset>
<fieldset class="radio">
<p>Radios:</p>
<label><input name="radio" type="radio" value="male" class="required"><span class="checked-icon"><span></span></span><span>Male</span></label>
<label><input name="radio" type="radio" value="female" class="required"><span class="checked-icon"><span></span></span><span>Female</span></label>
</fieldset>
<fieldset class="switch">
<p>Switch:</p>
<label><input name="switch" type="checkbox" value="On"><span><span></span></span></label>
</fieldset>
<button id="submit" type="submit">Send</button>
</form>
To get it work, you should specify in your HTML not name="selectFour" but name="selectFour[]"
EDIT: PHP side, you can exploit the $_REQUEST['selectFour'] as an array.
EDIT: So maybe, you can use implode function http://php.net/manual/en/function.implode.php

Can't get php contact form to work

I have a webpage that has two contact forms and the second one is working fine but I can't seem to get the first one to work. I am fairly new to php. Thanks in advance for the help. Here's the html:
<h3>Message Us</h3>
<form action="?" method="POST" onsubmit="return saveScrollPositions(this);">
<input type="hidden" name="scrollx" id="scrollx" value="0" />
<input type="hidden" name="scrolly" id="scrolly" value="0" />
<div id="msgbox1">
<label for="name2">Name:</label>
<input type="text" id="name2" name="name2" placeholder=" Required" />
<label for="email2">Email:</label>
<input type="text" id="email2" name="email2" placeholder=" Required" />
<label for="phone">Phone:</label>
<input type="text" id="phone" name="phone" placeholder="" />
<label for= "topic">Topic:</label>
<select id="topic" name="topic">
<option value="general">General</option>
<option value="stud">Property Price Enquiry</option>
<option value="sale">Bull Sale Enquiry</option>
</select>
</div><!--- msg box 1 -->
<div id="msgbox2">
<textarea id="message" name="message" rows="7" colums="25" placeholder="Your Message?"></textarea>
<p id="feedback2"><?php echo $feedback2; ?></p>
<input type="submit" value="Send Message" />
</div><!--- msg box 2 -->
</form><!--- end form -->
</div><!--- end message box -->
And here's the php:
<?php
$to2 = '418#hotmail.com'; $subject2 = 'MPG Website Enquiry';
$name2 = $_POST ['name2']; $email2 = $_POST ['email2']; $phone = $_POST ['phone']; $topic = $_POST ['topic']; $message = $_POST ['message'];
$body2 = <<<EMAIL
This is a message from $name2 Topic: $topic
Message: $message
From: $name2 Email: $email2 Phone: $phone
EMAIL;
$header2 = ' From: $email2';
if($_POST['submit']=='Send Message'){
if($name2 == '' || $email2 == '' || $message == ''){
$feedback2 = '*Please fill out all the fields';
}else {
mail($to2, $subject2, $body2, $header2);
$feedback2 = 'Thanks for the message. <br /> We will contact you soon!';
} } ?>
For the saveScrollPositions I use the following php and script:
<?php
$scrollx = 0;
$scrolly = 0;
if(!empty($_REQUEST['scrollx'])) {
$scrollx = $_REQUEST['scrollx'];
}
if(!empty($_REQUEST['scrolly'])) {
$scrolly = $_REQUEST['scrolly'];
}
?>
<script type="text/javascript">
window.scrollTo(<?php echo "$scrollx" ?>, <?php echo "$scrolly" ?>);
</script>
You have a mistake in your HTML part i.e.
<input type="submit" value="Send Message" />
add attribute name also in this input type like this-
<input type="submit" value="Send Message" name="submit" />
one thing more to correct in your php script is write-
$header2 = "From: ".$email2; instead of $header2 = ' From: $email2';
now try it.
What do you return in "saveScrollPositions" function? if you return false the form submit wont fire.

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>

Categories