I'm currently building my restaurant website and the included PHP form is quite limited. It's caused me a few headaches with reservations. What I'd like to do is create a 24 hour limit before each booking can be made. So if it's 1PM on 10/10/2013, a user cannot create a booking at 1:30PM on the 10/10/2013. The user will at minimal be able to make a booking at 11/10/2013 1PM.
On failure, I would like it to print an error message just like if there are failures in the other if statements.
I've been thinking of including something like this, but don't know where to start.
<?php
$t=date("H");
if ($t<"20")
{
echo "“Sorry, you need to book 24 hours in advance, please select another date.”;
}
else
{
$date = trim($_POST['datepick']);
}
?>
http://www.w3schools.com/php/php_if_else.asp
Below is the php reservation (contact form)
<?php
/**
* Template Name: Reservation
*
*/
$nameError = '';
$emailError = '';
$commentError = '';
$countError = '';
$dateError = '';
$timeError = '';
?>
<?php
global $de_data;
$de_data = get_option( 'Lezatos_options' );
$de_email = $de_data['DE_email_contact'];
$de_time_open = $de_data ['DE_time_open'];
$de_time_close = $de_data ['DE_time_close'];
$de_time_step = $de_data ['DE_time_step'];
$success_message = $de_data ['DE_booking_success_message'];
?>
<?php
if(isset($_POST['submitted'])) {
if(trim($_POST['contactName']) === '') {
$nameError = 'You forgot to enter your name.';
$hasError = true;
} else {
$name = trim($_POST['contactName']);
}
if(trim($_POST['email']) === '') {
$emailError = 'You forgot to enter your email address.';
$hasError = true;
} else if (!eregi("^[A-Z0-9._%-]+#[A-Z0-9._%-]+\.[A-Z]{2,4}$", trim($_POST['email']))) {
$emailError = 'You entered an invalid email address.';
$hasError = true;
} else {
$email = trim($_POST['email']);
}
if(function_exists('stripslashes')) {
$comments = stripslashes(trim($_POST['comments']));
} else {
$comments = trim($_POST['comments']);
}
if(trim($_POST['person_num']) === '') {
$countError = 'You forgot to enter your number of people.';
$hasError = true;
} else {
if(function_exists('stripslashes')) {
$person = stripslashes(trim($_POST['person_num']));
} else {
$person = trim($_POST['person_num']);
}
}
if(trim($_POST['datepick']) === '') {
$dateError = 'You forgot to enter your date.';
$hasError = true;
} else {
if(function_exists('stripslashes')) {
$date = stripslashes(trim($_POST['datepick']));
} else {
$date = trim($_POST['datepick']);
}
}
if(trim($_POST['time']) === '') {
$timeError = 'You forgot to enter your time.';
$hasError = true;
} else {
if(function_exists('stripslashes')) {
$time = stripslashes(trim($_POST['time']));
} else {
$time = trim($_POST['time']);
}
}
if(!isset($hasError)) {
if($de_email):
$email_address = $de_email;
else:
$email_address = 'designesia#gmail.com';
endif;
$emailTo = $email_address;
$subject = 'New Reservation';
$sendCopy = trim($_POST['sendCopy']);
$body = "Name: $name \n\nEmail: $email \n\nPerson: $person \n\nDate: $date \n\nTime: $time \n\nComments: $comments";
$headers = 'From: My Site <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $email;
mail($emailTo, $subject, $body, $headers);
if($sendCopy == true) {
$subject = 'You emailed Your Name';
$headers = 'From: Your Name <noreply#somedomain.com>';
mail($email, $subject, $body, $headers);
}
$emailSent = true;
}
} ?>
<?php get_header(); ?>
<div class="container">
<div class="eight columns"> </div>
<div class="eight columns booking_form_holder">
<?php if(get_option('DE_contact_text')<>''): ?>
<?php echo stripslashes(get_option('DE_contact_text')); ?>
<div style=" margin-bottom:20px;"></div>
<?php endif; ?>
<form action="<?php the_permalink(); ?>" id="contactForm" method="post">
<div id="de_form" class="booking_form">
<table class="table-form">
<tr>
<td><?php echo __('Name','Lezzatos'); ?></td>
<td><input type="text" name="contactName" id="contactName" value="<?php if(isset($_POST['contactName'])) echo $_POST['contactName'];?>" class="requiredField" />
<?php if($nameError != '') { ?>
<span class="error"></span>
<?php } ?></td>
</tr>
<tr>
<td><?php echo __('Email','Lezzatos'); ?></td>
<td><input type="text" name="email" id="email" value="<?php if(isset($_POST['email'])) echo $_POST['email'];?>" class="requiredField email" />
<?php if($emailError != '') { ?>
<span class="error"></span>
<?php } ?></td>
</tr>
<tr>
<td><?php echo __('Person','Lezzatos'); ?></td>
<td><input type="text" name="person_num" id="person_num" value="<?php if(isset($_POST['person_num'])) echo $_POST['person_num'];?>" class="requiredField" />
<?php if($countError != '') { ?>
<span class="error"></span>
<?php } ?></td>
</tr>
<tr>
<td><?php echo __('Date','Lezzatos'); ?></td>
<td><input type="text" name="datepick" id="datepick" value="<?php if(isset($_POST['datepick'])) echo $_POST['datepick'];?>" class="requiredField" />
<?php if($dateError != '') { ?>
<span class="error"></span>
<?php } ?></td>
</tr>
<tr>
<td><?php echo __('Time','Lezzatos'); ?></td>
<td><input type="text" name="time" id="time" value="<?php if(isset($_POST['time'])) echo $_POST['time'];?>" class="requiredField" />
<?php if($timeError != '') { ?>
<span class="error"></span>
<?php } ?></td>
</tr>
<tr>
<td><?php echo __('Comment','Lezzatos'); ?></td>
<td><textarea name="comments" id="commentsText" rows="6" cols="30" class="requiredField"><?php if(isset($_POST['comments'])) { if(function_exists('stripslashes')) { echo stripslashes($_POST['comments']); } else { echo $_POST['comments']; } } ?></textarea>
<?php if($commentError != '') { ?>
<span class="error"></span>
<?php } ?></td>
</tr>
<tr>
<td> </td>
<td><!--<input style="width:24px; display:inline-block;" type="checkbox" name="sendCopy" id="sendCopy" value="true"<?php //if(isset($_POST['sendCopy']) && $_POST['sendCopy'] == true) echo ' checked="checked"'; ?> />Send a copy of this email to yourself
<input type="text" name="checking" id="checking" class="screenReader" value="<?php if(isset($_POST['checking'])) echo $_POST['checking'];?>" /> -->
<input type="hidden" name="submitted" id="submitted" value="true" />
<button class="btn" type="submit"><?php echo __('SEND','Lezzatos'); ?></button></td>
</tr>
</table>
</form>
</div>
<?php if(isset($emailSent) && $emailSent == true) { ?>
<div class="thanks">
<?php
if($success_message){ echo $success_message;
}else{ echo 'Thank You! Your reservation was successfully sent.';
}
?>
</div>
<?php } ;?>
</div>
<div class="clear"></div>
</div>
</div>
<!-- ********** close content *********** -->
<script type='text/javascript' src='<?php echo get_template_directory_uri()?>/js/datepickr.js'></script>
<script type='text/javascript' src='<?php echo get_template_directory_uri()?>/js/jquery.timePicker.js'></script>
<script type="text/javascript">
new datepickr('datepick');
new datepickr('datepick2', {
'dateFormat': 'm/d/y'
});
new datepickr('datepick3', {
'fullCurrentMonth': false,
'dateFormat': 'l, F j'
});
</script>
<script type="text/javascript">
jQuery(function() {
$("#time").timePicker({
step:<?php if($de_time_step){echo $de_time_step;}else{ echo "60";}?>,
startTime:"<?php if($de_time_open){echo $de_time_open;}else{ echo "08:00";}?>",
endTime:"<?php if($de_time_close){echo $de_time_close;}else{ echo "22:00";}?>"
});
});
</script>
<?php get_footer(); ?>
Please guide me in the right direction.
EDIT:
This is the newly modified form which is treating all values entered into date as an error. Xor, I used the code you provided and modified to what I thought was right. I've also noticed that the form doesn't provide any of the errors defined within the code.
Below is a link to my website with the form:
http://tinyurl.com/pf8t9u4
EDIT #2:
Below is the new code that worked, it wouldn't allow a booking within 24 hours. However, I tried to make it display an error message about the 24 hour time failure. I mimicked the original method of displaying the success message using flagged variables, however it's failing. I created dateZoneError and date_failure_message. The error is
Parse error: syntax error, unexpected $end in /home/sol/public_html/wp-content/themes/lezzatos/page_reservation.php on line 252
The Code:
<?php
/**
* Template Name: Reservation
*
*/
$nameError = '';
$emailError = '';
$commentError = '';
$countError = '';
$dateError = '';
$timeError = '';
$time_restriction = strtotime("+1 day"); // 24 hours from now
$booking_time = strtotime($_POST['datepick']);
$dateZoneError= '';
?>
<?php
global $de_data;
$de_data = get_option( 'Lezatos_options' );
$de_email = $de_data['DE_email_contact'];
$de_time_open = $de_data ['DE_time_open'];
$de_time_close = $de_data ['DE_time_close'];
$de_time_step = $de_data ['DE_time_step'];
$success_message = $de_data ['DE_booking_success_message'];
$date_failure_message = $de_data ['DE_date_failure_message'];
?>
<?php
if(isset($_POST['submitted'])) {
if(trim($_POST['contactName']) === '') {
$nameError = 'You forgot to enter your name.';
$hasError = true;
} else {
$name = trim($_POST['contactName']);
}
if(trim($_POST['email']) === '') {
$emailError = 'You forgot to enter your email address.';
$hasError = true;
} else if (!eregi("^[A-Z0-9._%-]+#[A-Z0-9._%-]+\.[A-Z]{2,4}$", trim($_POST['email']))) {
$emailError = 'You entered an invalid email address.';
$hasError = true;
} else {
$email = trim($_POST['email']);
}
if(function_exists('stripslashes')) {
$comments = stripslashes(trim($_POST['comments']));
} else {
$comments = trim($_POST['comments']);
}
if(trim($_POST['person_num']) === '') {
$countError = 'You forgot to enter your number of people.';
$hasError = true;
} else {
if(function_exists('stripslashes')) {
$person = stripslashes(trim($_POST['person_num']));
} else {
$person = trim($_POST['person_num']);
}
}
if(trim($_POST['datepick']) === '') {
$dateError = 'You forgot to enter your date.';
$hasError = true;
} else {
if(function_exists('stripslashes')) {
$date = stripslashes(trim($_POST['datepick']));
} else {
$date = trim($_POST['datepick']);
}
}
if ($booking_time > $time_restriction ) {
// success ..
} else {
$dateZoneError = 'You need to book 24 hours';
$dateZoneError = true;
}
if(trim($_POST['time']) === '') {
$timeError = 'You forgot to enter your time.';
$hasError = true;
} else {
if(function_exists('stripslashes')) {
$time = stripslashes(trim($_POST['time']));
} else {
$time = trim($_POST['time']);
}
}
if(!isset($hasError)) {
if($de_email):
$email_address = $de_email;
else:
$email_address = 'designesia#gmail.com';
endif;
$emailTo = $email_address;
$subject = 'New Reservation';
$sendCopy = trim($_POST['sendCopy']);
$body = "Name: $name \n\nEmail: $email \n\nPerson: $person \n\nDate: $date \n\nTime: $time \n\nComments: $comments";
$headers = 'From: My Site <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $email;
mail($emailTo, $subject, $body, $headers);
if($sendCopy == true) {
$subject = 'You emailed Your Name';
$headers = 'From: Your Name <noreply#somedomain.com>';
mail($email, $subject, $body, $headers);
}
$emailSent = true;
}
} ?>
<?php get_header(); ?>
<div class="container">
<div class="eight columns"> </div>
<div class="eight columns booking_form_holder">
<?php if(get_option('DE_contact_text')<>''): ?>
<?php echo stripslashes(get_option('DE_contact_text')); ?>
<div style=" margin-bottom:20px;"></div>
<?php endif; ?>
<form action="<?php the_permalink(); ?>" id="contactForm" method="post">
<div id="de_form" class="booking_form">
<table class="table-form">
<tr>
<td><?php echo __('Name','Lezzatos'); ?></td>
<td><input type="text" name="contactName" id="contactName" value="<?php if(isset($_POST['contactName'])) echo $_POST['contactName'];?>" class="requiredField" />
<?php if($nameError != '') { ?>
<span class="error"></span>
<?php } ?></td>
</tr>
<tr>
<td><?php echo __('Email','Lezzatos'); ?></td>
<td><input type="text" name="email" id="email" value="<?php if(isset($_POST['email'])) echo $_POST['email'];?>" class="requiredField email" />
<?php if($emailError != '') { ?>
<span class="error"></span>
<?php } ?></td>
</tr>
<tr>
<td><?php echo __('Person','Lezzatos'); ?></td>
<td><input type="text" name="person_num" id="person_num" value="<?php if(isset($_POST['person_num'])) echo $_POST['person_num'];?>" class="requiredField" />
<?php if($countError != '') { ?>
<span class="error"></span>
<?php } ?></td>
</tr>
<tr>
<td><?php echo __('Date','Lezzatos'); ?></td>
<td><input type="text" name="datepick" id="datepick" value="<?php if(isset($_POST['datepick'])) echo $_POST['datepick'];?>" class="requiredField" />
<?php if($dateError != '') { ?>
<span class="error"></span>
<?php } ?></td>
</tr>
<tr>
<td><?php echo __('Time','Lezzatos'); ?></td>
<td><input type="text" name="time" id="time" value="<?php if(isset($_POST['time'])) echo $_POST['time'];?>" class="requiredField" />
<?php if($timeError != '') { ?>
<span class="error"></span>
<?php } ?></td>
</tr>
<tr>
<td><?php echo __('Comment','Lezzatos'); ?></td>
<td><textarea name="comments" id="commentsText" rows="6" cols="30" class="requiredField"><?php if(isset($_POST['comments'])) { if(function_exists('stripslashes')) { echo stripslashes($_POST['comments']); } else { echo $_POST['comments']; } } ?></textarea>
<?php if($commentError != '') { ?>
<span class="error"></span>
<?php } ?></td>
</tr>
<tr>
<td> </td>
<td><!--<input style="width:24px; display:inline-block;" type="checkbox" name="sendCopy" id="sendCopy" value="true"<?php //if(isset($_POST['sendCopy']) && $_POST['sendCopy'] == true) echo ' checked="checked"'; ?> />Send a copy of this email to yourself
<input type="text" name="checking" id="checking" class="screenReader" value="<?php if(isset($_POST['checking'])) echo $_POST['checking'];?>" /> -->
<input type="hidden" name="submitted" id="submitted" value="true" />
<button class="btn" type="submit"><?php echo __('SEND','Lezzatos'); ?></button></td>
</tr>
</table>
</form>
</div>
<?php if(isset($emailSent) && $emailSent == true) { ?>
<div class="thanks">
<?php
if($success_message){ echo $success_message;
}else{ echo 'Thank You! Your reservation was successfully sent.';
}
?>
</div>
<?php } ;?>
<?php if(isset($dateZoneError) && $dateZoneError== true) { ?>
<div class="failure">
<?php
if($date_failure_message){ echo $date_failure_message;
}else{ echo 'You need to allow 24 hours between now and the selected booking date.';
}
?>
</div>
</div>
<div class="clear"></div>
</div>
</div>
<!-- ********** close content *********** -->
<script type='text/javascript' src='<?php echo get_template_directory_uri()?>/js/datepickr.js'></script>
<script type='text/javascript' src='<?php echo get_template_directory_uri()?>/js/jquery.timePicker.js'></script>
<script type="text/javascript">
new datepickr('datepick');
new datepickr('datepick2', {
'dateFormat': 'm/d/y'
});
new datepickr('datepick3', {
'fullCurrentMonth': false,
'dateFormat': 'l, F j'
});
</script>
<script type="text/javascript">
jQuery(function() {
$("#time").timePicker({
step:<?php if($de_time_step){echo $de_time_step;}else{ echo "60";}?>,
startTime:"<?php if($de_time_open){echo $de_time_open;}else{ echo "08:00";}?>",
endTime:"<?php if($de_time_close){echo $de_time_close;}else{ echo "22:00";}?>"
});
});
</script>
<?php get_footer(); ?>
You should have been more precise about your question like the column type you are saving your date in the database table, whether it is date time or timestamp etc, but anyway the logic is to check whether the current time is lesser or greater than 24 hours of booking time. if lesser than 24 hours pass an error, or else add to the database
$time_restriction = strtotime("+1 day"); // 24 hours from now
$booking_time = strtotime($_POST['datepick']); // time of checking in
if ($booking_time > $time_restriction ) {
// success ..
} else {
// error
// you cannot book prior to 24 hours
}
/*edit --------*/
seems like its a syntax error, you might have missed a closing curly braces or something. but to be honest your error parsing method is too complicated. I would suggest you to store the errors in an array and check if its empty before you add or insert the data's into the database.
for ex :
$errors = array();
if(trim($_POST['contactName']) === '') {
$errors[] = 'You forgot to enter your name.';
} else {
$name = trim($_POST['contactName']);
}
if(trim($_POST['datepick']) === '') {
$errors[] = 'You forgot to enter your date.';
} else {
if(function_exists('stripslashes')) {
$date = stripslashes(trim($_POST['datepick']));
} else {
$date = trim($_POST['datepick']);
}
}
if(empty($errors)) {
// add datas into the database
} else {
// errors found
foreach ($errors as $error ) {
echo $error;
}
}
Related
I've got this wordpress site with a custom post type, called reviews, loop and a contact form on a page. When I click on the submit button on the contact page, reguardless if the form contents matches the regex, it redirects the page to /reviewa/random name
I've removed the "reviews" part of the website and the form works.
What I would like to happen is to have the form send the email, without redirecting the site to /reviews/randomName
$(function() {
var re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
$('#contact-form').submit(function(e) {
$clientName = $("#contactName").val();
var valid = true;
// Remove any confirmation messages
$('p.confirmation').remove();
// Validate all fields that have a class of .required-field
$('.required-field').each(function() {
// Remove error class from all inputs and textareas and delete error messages before checking form again
$(this).removeClass('error').next('p').remove();
if ($(this).val().trim() === '' && $(this).attr('id') != 'email') {
$(this).addClass('error').parent().append('<p class="error">Please enter a ' + $(this).prev().html().toLowerCase() + '</p>');
valid = valid && false;
} else if ($(this).attr('id') === 'email') {
if (!$(this).val().trim().match(re)) {
$(this).addClass('error').parent().append('<p class="error">Please enter a valid email address</p>');
valid = valid && false;
}
}
});
if (valid) {
var formInput = $(this).serialize();
$.post($(this).attr('action'), formInput, function(data) {
$('#contact-form').before('<p class="confirmation">Thanks ' + $clientName + ', your email was successfully sent. We will be in touch soon.</p>');
_gaq.push(['_trackEvent', 'Contact form', 'Contact form submitted']);
});
}
e.preventDefault();
});
});
<div id="reviews">
<h2>Our reviews</h2>
<div id="slider" class="flex-container">
<div class="flexslider">
<ul class="slides">
<?php $new = new WP_Query('post_type=reviews& posts_per_page=-1');
while ($new->have_posts()) : $new->the_post(); ?>
<li>
<?php echo the_post_thumbnail('portfolio-thumb');?>
<span class="review"> <?php the_content(); ?></span>
<span class="name"> <?php the_title(); ?></span>
</li>
<?php endwhile;?>
</ul>
</div>
</div>
</div>
<div id="contact">
<h2>To contact the instructor, plese enter your details below</h2>
<?php
if($_SERVER['REQUEST_METHOD'] == "POST" && isset($_POST['submitted'])){
//Check name
if(trim($_POST['contactName']) === '') {
$nameError = true;
$hasError = true;
}else{
$name = trim($_POST['contactName']);
}
//Check company name
if(trim($_POST['companyName']) === '') {
$companyNameError = true;
$companyNameError = true;
}else{
$companyName = trim($_POST['companyName']);
}
//Check address
if(trim($_POST['address']) === '') {
$addressError = true;
$addressError = true;
}else{
$address = trim($_POST['address']);
}
// Check email address exists and is valid
if(trim($_POST['email']) === '') {
$emailError = 'Please enter your email address.';
$hasError = true;
}else if (!eregi("^[A-Z0-9._%-]+#[A-Z0-9._%-]+.[A-Z]{2,4}$",trim($_POST['email']))){
$emailError = 'You entered an invalid email address.';
$hasError = true;
}else{
$email = trim($_POST['email']);
}
if(trim($_POST['telNumber']) === '') {
$telError = true;
$hasError = true;
}else{
$telephone = trim($_POST['telNumber']);
}
//Check message
if(trim($_POST['message']) === ''){
$messageError = true;
$hasError = true;
}else{
$message = stripslashes(trim($_POST['message']));
}
//If there is no error, send the email
if(!isset($hasError)){
$emailTo = 'randomEmail#mail.com';
$subject = 'Contact from the Contact Us page';
$body = "Name: $name \n Email: $email \n Telephone: $telephone \n Poxtcode: $address . \n Message:\n$message";
$headers = 'From: randomWebsite.com, <'.$emailTo.'>' . "\n" . "\n" .'Reply-To: ' . $email;
ssmtp($emailTo, $subject, $body, $headers);
$emailSent = true;
}
}
?>
<?php if($emailSent == true) { ?>
<p class="confirmation">Thanks,
<?php echo $name;?>, your email was successfully sent. We will be in touch soon.</p>
<?php } ?>
<form action="<?php the_permalink(); ?>" id="contact-form" method="post" novalidate>
<ul>
<li>
<input type="text" placeholder="Name (required)" name="contactName" id="contactName" value="<?php if(isset($_POST['contactName'])){echo $_POST['contactName'];} ?>" class="required-field" />
<?php if($nameError) { ?>
<p class="error">Please enter your name.</p>
<?php } ?>
</li>
<li>
<input type="text" placeholder="Postcode (required)" name="address" id="address" value="<?php if(isset($_POST['address'])){echo $_POST['address'];} ?>" class="required-field" />
<?php if($addressError) { ?>
<p class="error">Please enter your postcode.</p>
<?php } ?>
</li>
<li>
<input type="tel" placeholder="Mobile number (required)" name="telNumber" id="telNumber" value="<?php if(isset($_POST['telNumber'])){echo $_POST['telNumber'];} ?>" />
<?php if($telError) { ?>
<p class="error">Please enter your mobile number.</p>
<?php } ?>
</li>
<li>
<input type="email" placeholder="Email (required)" name="email" id="email" value="<?php if(isset($_POST['email'])){echo $_POST['email'];} ?>" class="required-field" />
<?php if($emailError) { ?>
<p class="error">
<?php echo $emailError;?>
</p>
<?php } ?>
</li>
<li class="textarea">
<textarea name="message" placeholder="Message (required)" id="message" rows="20" cols="30" class="required-field"><?php if(isset($_POST['message'])){echo stripslashes($_POST['message']);} ?></textarea>
<?php if($messageError) { ?>
<p class="error">Please enter a message.</p>
<?php } ?>
</li>
<li>
<input type="hidden" id="submitted" name="submitted" />
<button class="button" ">Send</button>
</li>
</ul>
</form>
</div>
I have a simple contact form in a Wordpress website, that needs some protecting.
I gave it two empty fields named "website" and "email" and hid them with CSS (visibility: hidden;). So far, so good.
The problem now is, I just cannot give the PHP commands
if(isset($_POST['website'])) die();
if(isset($_POST['email'])) die();
the proper position in my PHP file. Can you tell me where to position it correctly?
Here is my PHP file:
<?php
if(isset($_POST['website'])) die();
if(isset($_POST['email'])) die();
if(isset($_POST['submitted'])) {
if(trim($_POST['contactVorname']) === '') {
$vornameError = '*';
$hasError = true;
} else {
$vorname = trim($_POST['contactVorname']);
}
if(trim($_POST['contactName']) === '') {
$nameError = '*';
$hasError = true;
} else {
$name = trim($_POST['contactName']);
}
if(trim($_POST['contactEmail']) === '') {
$emailError = '*';
$hasError = true;
} else if (!preg_match("/^[[:alnum:]][a-z0-9_.-]*#[a-z0-9.-]+\.[a-z]{2,4}$/i", trim($_POST['contactEmail']))) {
$emailError = '*';
$hasError = true;
} else {
$email = trim($_POST['contactEmail']);
}
if(trim($_POST['unternehmen']) === '') {
/* $unternehmenError = '*';
$hasError = true; */
} else {
$unternehmen = trim($_POST['unternehmen']);
}
if(trim($_POST['ort']) === '') {
/* $ortError = '*';
$hasError = true; */
} else {
$ort = trim($_POST['ort']);
}
if(trim($_POST['telefon']) === '') {
/* $telefonError = '*';
$hasError = true; */
} else {
$telefon = trim($_POST['telefon']);
}
if(trim($_POST['betreff']) === '') {
$betreffError = '*';
$hasError = true;
} else {
$betreff = trim($_POST['betreff']);
}
if(trim($_POST['comments']) === '') {
$commentError = '*';
$hasError = true;
} else {
if(function_exists('stripslashes')) {
$comments = stripslashes(trim($_POST['comments']));
} else {
$comments = trim($_POST['comments']);
}
}
if(!isset($hasError)) {
$emailTo = get_option('tz_email');
if (!isset($emailTo) || ($emailTo == '') ){
$emailTo = get_option('admin_email');
}
$subject = 'Kontaktformular | '.$vorname.' '.$name;
$body = "\n.: Kontaktformular-E-Mail :. \n\nName: $vorname $name \nE-Mail: $email \n\nUnternehmen: $unternehmen \nOrt: $ort \nTelefon: $telefon \n\nBetreff: $betreff \n\nNachricht: $comments";
$headers = 'From: '.$vorname.' '.$name.' <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $email;
wp_mail($emailTo, $subject, $body, $headers);
$emailSent = true;
}
}
?>
<?php get_header(); ?>
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<article class="post" id="post-<?php the_ID(); ?>">
<h2 class="gross"><?php the_title(); ?></h2>
<div id="inhalt">
<div class="seitebeitrag">
<?php if(isset($emailSent) && $emailSent == true) { ?>
<div><p>Vielen Dank für die Nachricht. Wir melden uns so schnell wie möglich zurück.</p></div>
<?php } else { ?>
<?php the_content(); ?>
<form action="" id="contactForm" method="post">
<div id="kf0"> </div>
<div id="kf1">
<p><label for="contactVorname">Vorname *</label><br />
<input type="text" name="contactVorname" id="contactVorname" value="<?php if(isset($_POST['contactVorname'])) echo $_POST['contactVorname'];?>" maxlength="50" />
<?php if(!empty($vornameError)) { ?>
<span class="fehler"><?=$vornameError;?></span>
<?php } ?></p>
<p><label for="contactName">Nachname *</label><br />
<input type="text" name="contactName" id="contactName" value="<?php if(isset($_POST['contactName'])) echo $_POST['contactName'];?>" maxlength="50" />
<?php if(!empty($nameError)) { ?>
<span class="fehler"><?=$nameError;?></span>
<?php } ?></p>
<p><label for="contactEmail">E-Mail *</label><br />
<input type="text" name="contactEmail" id="contactEmail" value="<?php if(isset($_POST['contactEmail'])) echo $_POST['contactEmail'];?>" maxlength="50" />
<?php if(!empty($emailError)) { ?>
<span class="fehler"><?=$emailError;?></span>
<?php } ?></p>
<p><label for="unternehmen">Unternehmen</label><br />
<input type="text" name="unternehmen" id="unternehmen" value="" maxlength="50" /></p>
<p><label for="ort">Ort</label><br />
<input type="text" name="ort" id="ort" value="" maxlength="50" /></p>
<p><label for="telefon">Telefon</label><br />
<input type="text" name="telefon" id="telefon" value="" maxlength="50" /></p>
<input type="text" id="website" name="website" value="" maxlength="80" /><br />
<input type="text" id="email" name="email" value="" maxlength="80" />
</div>
<div id="kf2">
<p><label for="betreff">Betreff *</label><br />
<input type="text" name="betreff" id="betreff" value="<?php if(isset($_POST['betreff'])) echo $_POST['betreff'];?>" maxlength="50" />
<?php if(!empty($betreffError)) { ?>
<span class="fehler"><?=$betreffError;?></span>
<?php } ?></p>
<p><label for="commentsText">Nachricht *</label><br />
<textarea name="comments" id="commentsText" rows="20" cols="30"><?php if(isset($_POST['comments'])) { if(function_exists('stripslashes')) { echo stripslashes($_POST['comments']); } else { echo $_POST['comments']; } } ?></textarea>
<?php if(!empty($commentError)) { ?>
<span class="fehler"><?=$commentError;?></span>
<?php } ?></p>
<p>* Pflichtfelder</p>
</div>
<div id="kf3">
<input type="submit" value="SENDEN" alt="senden" class="btn" /><br /><input type="hidden" name="submitted" id="submitted" value="true" />
</div>
<div id="kf4">
<?php if(isset($hasError) || isset($captchaError)) { ?>
<div><p class="error fehler">* ungültige oder fehlende Daten</p></div>
<?php } ?></div>
</form>
<?php } ?>
<?php wp_link_pages(array('before' => __('Pages: '), 'next_or_number' => 'number')); ?>
</div>
<?php // edit_post_link(__('Edit this entry.'), '<p>', '</p>'); ?>
</article>
<?php // comments_template(); ?>
<?php endwhile; endif; ?>
<?php // get_sidebar(); ?>
<?php get_footer(); ?>
Right now, the form gets totally blocked out, after sending the data, ALTHOUGH the two fields in question are NOT FILLED IN.
$_POST['website'] & $_POST['email'] will always be 'set'. An empty form field still sets the corresponding $_POST entry to an empty string ('') and will always be true to isset. Try using !empty.
if (!empty($_POST['website'])) die();
if (!empty($_POST['email'])) die();
See more here: http://php.net/manual/en/function.empty.php and with a bit more detail here: https://www.virendrachandak.com/techtalk/php-isset-vs-empty-vs-is_null/
Be careful using this approach with commonly named fields. They may be automatically filled in by a browser's auto-fill feature meaning you'll be getting false-positives and real users will end up on a blank screen.
I have a well working contact form on my site. Now I'm trying to include a math captcha to the from. Unfortunately, I was not able to make it work. Any idea how (where) to include the captcha codes?
I tried a lot of things, but it does not work properly. Maybe the code is not the best :) I already searched for a solution in stackoverflow and google with no luck.
My working contact form at the moment:
<?php
if(isset($_POST['submitted'])) {
if(trim($_POST['contactName']) === '') {
$nameError = sprintf( __( 'Please enter your name.', 'test_theme' ) );
$hasError = true;
} else {
$name = trim($_POST['contactName']);
}
if(trim($_POST['email']) === '') {
$emailError = sprintf( __( 'Please enter your email address.', 'test_theme' ) );
$hasError = true;
} else if (!preg_match("/^[[:alnum:]][a-z0-9_.-]*#[a-z0-9.-]+\.[a-z]{2,4}$/i", trim($_POST['email']))) {
$emailError = sprintf( __( 'You entered an invalid email address.', 'test_theme' ) );
$hasError = true;
} else {
$email = trim($_POST['email']);
}
if(trim($_POST['comments']) === '') {
$commentError = sprintf( __( 'Please enter a message.', 'test_theme' ) );
$hasError = true;
} else {
if(function_exists('stripslashes')) {
$comments = stripslashes(trim($_POST['comments']));
} else {
$comments = trim($_POST['comments']);
}
}
if(!isset($hasError)) {
$emailTo = get_option('tz_email');
if (!isset($emailTo) || ($emailTo == '') ){
$emailTo = get_option('admin_email');
}
$subject = sprintf( __( 'Contact Form', 'test_theme' ) );
$body = "Name: $name \n\nMail: $email \n\n $comments";
$headers = 'From: '.$name.' <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $email;
wp_mail($emailTo, $subject, $body, $headers);
$emailSent = true;
}
} ?>
<?php if(isset($emailSent) && $emailSent == true) { ?>
<div class="thanks">
<p><?php _e( 'Thanks, your email was sent successfully.', 'test_theme' ); ?></p>
</div>
<?php } else { ?>
<?php if(isset($hasError) || isset($captchaError)) { ?>
<p class="error-conform"><?php _e( 'Sorry, an error occured.', 'test_theme' ); ?><p>
<?php } ?>
<form action="<?php the_permalink(); ?>" class="author-description" id="contactForm" method="post">
<h2><?php _e( 'Contact Us', 'test_theme' ); ?></h2><br />
<p><label for="contactName"><?php _e( 'Your Name', 'test_theme' ); ?> <span>*</span>
<?php if($nameError != '') { ?>
<span class="error-conform"><?=$nameError;?></span>
<?php } ?><br />
<input type="text" name="contactName" id="contactName" value="<?php if(isset($_POST['contactName'])) echo $_POST['contactName'];?>" /></label></p>
<p><label for="email"><?php _e( 'Your Email Adress', 'test_theme' ); ?> <span>*</span>
<?php if($emailError != '') { ?>
<span class="error-conform"><?=$emailError;?></span>
<?php } ?><br />
<input type="text" name="email" id="email" value="<?php if(isset($_POST['email'])) echo $_POST['email'];?>" /></label></p>
<p><label for="commentsText"><?php _e( 'Your Message', 'test_theme' ); ?> <span>*</span>
<?php if($commentError != '') { ?>
<span class="error-conform"><?=$commentError;?></span>
<?php } ?><br />
<textarea type="text" name="comments" id="commentsText" rows="20" cols="30"><?php if(isset($_POST['comments'])) { if(function_exists('stripslashes')) { echo stripslashes($_POST['comments']); } else { echo $_POST['comments']; } } ?></textarea></label></p>
<p><input type="submit"></p>
<input type="hidden" name="submitted" id="submitted" value="true" />
</form>
<?php } ?>
Captcha Code that should included in the contact form above:
Part 1:
if(!isset($_POST['submitted'])) {
session_start();
$digit1 = mt_rand(1,6);
$digit2 = mt_rand(1,6);
$math = "$digit1 + $digit2";
$_SESSION['answer'] = $digit1 + $digit2;
}
Part 2:
if ($_SESSION['answer'] != $_POST['answer'] ) {
$mathError = 'Please answer the math question.';
$hasError = true;
}
Part 3:
<span class="error-conform"><?=$mathError;?></span>
<li><label>What's <?php echo $math; ?> = </label><input name="answer" type="text" /></li>
I guess this will give you some ideas.
<?php
session_start(); // session start should be the very first line of your php code, for session management
// checking whether the form is being submitted by the user
if( isset($_POST['submitted']) )
{
// checking whether the user submitted answer matches with the captcha
if ($_SESSION['answer'] != $_POST['answer'] )
{
$mathError = 'Please answer the math question.';
$hasError = true;
}
// ....
// do other form validations here..
// ....
if( !$hasError )
{
// no errors, so send the mail or do whatever you want to do here...
}
}
// now generating new captcha
$digit1 = mt_rand(1,6);
$digit2 = mt_rand(1,6);
$math = "$digit1 + $digit2";
$_SESSION['answer'] = $digit1 + $digit2;
?>
<!-- html goes here --->
<forma ction="<?php the_permalink(); ?>
<!-- include the form fields here... -->
<?php if(!empty($mathError)) { ?>
<span class="error-conform"><?php echo $mathError; ?></span>
<?php } ?>
<label>What's <?php echo $math; ?> = </label><input name="answer" type="text" />
<input type="hidden" name="submitted" id="submitted" value="true" />
</form>
<!-- rest of the html goes here --->
I have separate email script; however, how would we run that code if there are no errors. I have a array with form errors $errors = array($nameErr, $emailErr, $phoneErr, $zipErr, $serviceErr); but they have different strings, if there are no strings or Null or '' inside the array, we would like to send email.
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
// define variables and set to empty values
$nameErr = $phoneErr = $emailErr = $zipErr = $serviceErr = "";
$name = $phone = $email = $zip = $service = $comment = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "name required.";
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "letters and spaces only.";
}
}
if (empty($_POST["email"])) {
$emailErr = "email required.";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "invalid email format.";
}
}
if (empty($_POST["phone"])) {
$phoneErr = "phone required.";
} else {
//Check phone for numbers () or - only
$phone = test_input($_POST["phone"]);
if (!preg_match("/^[\+0-9\-\(\)\s]*$/", $phone)) {
$phoneErr = "format.";
}
}
if (empty($_POST["zip"])) {
$zipErr = "zip required.";
} else {
$zip = test_input($_POST["zip"]);
}
if (!preg_match("/^[\+0-9\-\(\)\s]*$/", $zip)){
$zipErr = "format.";
}
if ($_POST["service"] == NULL ) {
$serviceErr = "service required.";
}else {
$service = test_input($_POST["service"]);
}
$comment = test_input($_POST["comment"]);
//**********************************************************************
$errors = array($nameErr, $emailErr, $phoneErr, $zipErr, $serviceErr);
if (isset($_POST['Submit'])) {
//if no errors run send email CODE.
}
//***********************************************************************
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<form <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<table>
<tr>
<td> Name:
<br />
<input name="name" type="text" size="20" value="<?php echo $name;?>">
<span class="error">* <?php echo "<br />"; echo $nameErr;?></span>
</td>
</tr>
<tr>
<td> Phone:
<br />
<input name="phone" type="text" size="20" value="<?php echo $phone;?>">
<span class="error">* <?php echo "<br />"; echo $phoneErr;?></span>
</td>
</tr>
<tr>
<td> E-mail:
<br />
<input name="email" type="text" size="20" value="<?php echo $email;?>">
<span class="error">* <?php echo "<br />"; echo $emailErr;?></span>
</td>
</tr>
<tr>
<td> Zip:
<br />
<input name="zip" type="text" size="20" value="<?php echo $zip;?>">
<span class="error">* <?php echo "<br />"; echo $zipErr;?></span>
</td>
</tr>
<tr>
<td> Service:
<br />
<select name="service">
<option selected="selected" value="<?php echo $service;?>"><?php echo $service;?></option>
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
<option value="D">D</option>
</select>
<span class="error">* <?php echo "<br />"; echo $serviceErr;?></span>
</td>
</tr>
<tr>
<td> Message:
<br />
<textarea name="comment" rows="2" cols="20"><?php echo $comment;?></textarea></td>
</tr>
<tr>
<td>
<input type="submit" name="Submit" value="Send" />
</td>
</tr>
</table>
</form>
<?php
echo "<h2>Your Input:</h2>";
echo $name;
echo "<br>";
echo $email;
echo "<br>";
echo $phone;
echo "<br>";
echo $zip;
echo "<br>";
echo $service;
echo "<br>";
echo "$comment";
?>
</body>
</html>
try with the below code:
$errors = array($nameErr, $emailErr, $phoneErr, $zipErr, $serviceErr);
if (isset($_POST['Submit'])) {
if(!array_filter($errors)){
// code here
}
else {
echo "Error";
}
}
Save your errors in an array, then check if the array is empty at the end. If so, no errors - submit email. Else, display errors:
//dont declare separate variables,use an array
//$nameErr = $phoneErr = $emailErr = $zipErr = $serviceErr = "";
$errors = [];
if (empty($_POST["name"])) {
$errors['nameErr'] = "name required.";
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$errors['nameErr'] = "letters and spaces only.";
}
}
//other validation here, then
if(empty($errors){
//no errors, submit
your_submit_function();
}else{
//display errors
foreach($errors as $val){
echo $val . '<br/>';
}
}
Link to website: http://www.leonardpfautsch.com/contact.php
How do I make my contact form validated only using PHP? I want to be able to have error messages directly under the text field that has an error. For each text field, I do not want multiple errors to show up at once. If you submit the form with nothing in the fields, you see that under name and email two errors show up for each. I want the errors to show up only once due to some type of specifications. Right now I think I am on the right track. However, the code below does not have the email being sent. I am very new to PHP. If anybody could help me, I would really appreciate it.
<?php
if (($_SERVER['REQUEST_METHOD'] == 'POST') && (!empty($_POST['action']))){
$errors = array($name_error_1, $name_error_2, $email_error_1, $email_error_2, $subject_error, $message_error);
$name = $_POST['name'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$message = $_POST['message'];
if ($name === '') {
$name_error_1 = '<div style="color:red;"> Name is a required field! </div>';
}
if ($email === '') {
$email_error_1 = '<div style="color:red;"> Email is a required field! </div>';
}
if ($subject === '') {
$subject_error = '<div style="color:red;"> Subject is a required field! </div>';
}
if ($message === '') {
$message_error = '<div style="color:red;"> Message is a required field! </div>';
}
if (isset($email) && (filter_var($email, FILTER_VALIDATE_EMAIL) === false)){
$email_error_2 = '<div style="color:red;"> The email address must be real! </div>';
}
if (ctype_alpha($name) === false) {
$name_error_2 = '<div style="color:red;"> Your name must only contain letters! </div>';
}
/*Main way that mail works*/
if (empty($errors) === true) {
/*Where_mail_goes_to, Subject, Body_text, Who_email_is_from*/
mail('email_address', $subject, "From " . $name . "\r\r" . $message, 'From: ' . $email);
/*Shows up in the URL if the message has been sent*/
header('Location: contact.php?sent');
exit();
}
} //end of main if
?>
<form method="POST" action="<?php echo $_SERVER['PHP_SELF'] ?>" >
<span class="label">Name</span><br/>
<?php if (isset($name_error_1)) { echo $name_error_1; } ?>
<?php if (isset($name_error_2)) { echo $name_error_2; } ?>
<input type="text" class="textfield" name="name" size="50" maxlength="50" <?php if (isset($_POST['name']) === true) { echo 'value="', strip_tags($_POST['name']), '"'; } ?> > <br/>
<span class="label">Email</span><br/>
<?php if (isset($email_error_1)) { echo $email_error_1; } ?>
<?php if (isset($email_error_2)) { echo $email_error_2; } ?>
<input type="text" class="textfield" name="email" size="50" maxlength="50" <?php if (isset($_POST['email']) === true) { echo 'value="', strip_tags($_POST['email']), '"'; } ?> > <br/>
<span class="label">Subject</span><br/>
<?php if (isset($subject_error)) { echo $subject_error; } ?>
<input type="text" class="textfield" name="subject" size="50" maxlength="50" <?php if (isset($_POST['subject']) === true) { echo 'value="', strip_tags($_POST['subject']), '"'; } ?> > <br/>
<span class="label">Message</span><br/>
<?php if (isset($message_error)) { echo $message_error; } ?>
<textarea rows="5" cols="50" name="message" id="textarea" maxlength="500"><?php if (isset($_POST['message']) === true){ echo $_POST['message'];}?></textarea><br/>
<input type="submit" value="Send" id="submit" name="action">
</form>
You could create an array of errors for each field and display just the first error added to it.
<?php
$email_errors = array();
if ($email == '')
{
$email_errors[] = 'First error';
}
if (more_email_checks($email) == false)
{
$email_errors[] = 'Second error';
}
?>
...
<span class="label">Email</span><br />
<?php echo array_shift($email_errors); ?>
To know whether to send e-mails or not, you could do something like this:
$errors_found = 0;
if (check_email($email) == false)
{
$email_error = 'Error message';
$errors_found++;
}
...
if ($errors_found == 0)
{
mail(...);
}
You can do it by using the elseif check
<span class="label">Email</span><br/>
<?php if (isset($email_error_1))
{
echo $email_error_1;
}
elseif(isset($email_error_2)) {
echo $email_error_2;
} ?>
Also move this line after the last validation check
if (ctype_alpha($name) === false) {
$name_error_2 = '<div style="color:red;"> Your name must only contain letters! </div>';
}
$errors = array($name_error_1, $name_error_2, $email_error_1, $email_error_2, $subject_error, $message_error);
you can by this code for name
<?
$message = "<div style = 'color :red ' /> ;
if (isset(name == '' ) {
echo $message
}
?>
this is name php vaildation but yo can create js
Change your email validation to:
<span class="label">Email</span><br/>
<?php if (isset($email_error_1))
{
echo $email_error_1;
}else if(isset($email_error_2)) {
echo $email_error_2;
} ?>
same if else can be applied to all the fields with multiple validation conditions.
and then move your error array just above the email condition check:
<?php
$errors = array($name_error_1, $name_error_2, $email_error_1, $email_error_2, $subject_error, $message_error);
//and change your mail function as:
$to = 'email_address';
$headers = $headers .= 'From: $name <$email>';
mail($to, $subject, $message, $headers);
?>
Also perform a check on the control, if you have filled the form completely then it should come to the mail function, I mean just check the if condition, in case you have some issue with the condition, try to put an echo inside if statement(which is responsible for sending email), and if that echo statement executes then mail should work.
:)