I am stuck in bit of a situation here. So the issue is that I have a simple form which gets the data using $_POST and emails the data to a email (I am using PHPMailer). Now I have to integrate a Paypal button in it so that the client could be redirected to the Paypal page for payment, the issue is that the Paypal button is a form and it has its own action and I am not sure how to apply both (Paypal and Emailing) actions together in the same form. Can someone please guide me here?
Emailing Form:
<form action="process-email.php" class="floatfix" id="card-form" method="post" data-message="Thank you for purchasing. We will contact you via email." enctype="multipart/form-data">
<div class="flt-l left">
<div class="field-container">
<div class="field-number">1</div>
<h3 class="txt-a-c h3-title"><img src="img/icons/clipboard.png" alt="">Place your Order</h3>
<div class="form-panels floatfix clr-b">
<div class="flt-l left-side-panel">
<div id="form-contact-details-container" class="form-contact-details-container">
<input type="text" tabindex="10" required value="Full Name" name="full-name">
<input type="text" tabindex="20" required value="Office #" name="office">
<input type="text" tabindex="30" required value="Mobile #" name="mobile">
<input type="text" tabindex="40" required value="Email" name="email">
<input type="text" tabindex="50" required value="Website" name="website">
</div>
<div class="card-styles floatfix">
Card Style
</div>
<div class="card-shots">
<div class="card-shot pos-r floatfix">
<input type="radio" name="body_shots" id="card-shot-none" data-card-shot-type="none" value="Full Shot" checked class="active">
<span class="radio">No <br>Shot</span>
<img src="img/card_empty.png" alt="" class="card-empty-img">
<div class="check-mark"><img src="img/icons/check_round.png" alt=""></div>
</div>
<div class="card-shot pos-r floatfix">
<input type="radio" name="body_shots" id="card-shot-half" data-card-shot-type="half" value="Half Shot">
<span class="radio">Half Body <br>Shot</span>
<img src="img/card_half_pic.png" alt="">
<div class="check-mark"><img src="img/icons/check_round.png" alt=""></div>
</div>
<div class="card-shot pos-r floatfix">
<input type="radio" name="body_shots" id="card-shot-full" data-card-shot-type="full" value="Full Shot">
<span class="radio">Full Body <br>Shot</span>
<img src="img/card_full_pic.png" alt="">
<div class="check-mark"><img src="img/icons/check_round.png" alt=""></div>
</div>
</div>
<div id="upload-container" class="noselect notify-hover upload-container">
<div class="inner">
<div id="upload-preview" class="page-cover upload-img-container"></div>
<div class="upload-text">Upload Your Photo <span class="camera"></span></div>
<input id="upload-file" class="upload-file" type="file" name="upload-file[]" multiple="multiple">
</div>
<div class="notify">
<h6 class="fnt-w-b">Only Upload files less than 2mb.</h6>
<p>Please allow 2 Business Days for Photo Filtering and Processing.</p>
</div>
</div>
<div class="pos-r notify-hover shipping-address">
<input id="shipping-address-1" type="text" placeholder="Shipping Address" tabindex="60" name="shipping_address_1">
<span id="shipping-address-1-holder" class="pos-a hidden"></span>
<input id="shipping-address-2" type="text" tabindex="70" name="shipping_address_2">
<span id="shipping-address-2-holder" class="pos-a hidden"></span>
<div class="notify">
<p>Carefully Fill this as we do not offer refund on lost packages.</p>
</div>
</div>
</div>
<div class="flt-r right-side-panel">
<span class="noselect crs-p card-flipper">See <span data-before="Back" data-after="Front"></span> of Card</span>
<div class="pos-r">
<div id="the-card" class="noselect card-preview-container">
<div class="card card-front">
<div class="full-before full-after card-pic"></div>
<div id="card-detail-preview-container" class="card-detail-preview noselect crs-d"></div>
</div>
<div class="card card-back"><img src="img/card_back.png" alt=""></div>
</div>
</div>
</div>
</div>
<div class="submit-button-container">
<input type="submit" value="" id="card-form-submit">
<div class="submit-button">
<h2 class="txt-t-u">$125 - Order Now</h2>
<div>1000 Business Cards</div>
</div>
<img src="img/paypal.png" alt="" class="paypal">
<p class="small txt-a-c">You will be takend to Paypal for payment processing</p>
</div>
</div>
</div>
<div class="flt-r right">
<div class="field-container">
<div class="field-number">2</div>
<div class="checkbox-container">
<div class="checkbox">
<img src="img/icons/check.png" alt="">
</div>
<span class="label">Approve & Receive It</span>
</div>
<p class="p-1">You will receive a PDF of the final card with your processed photo.</p>
<p class="p-2">You will receive your order within 7-10 business days.</p>
</div>
</div>
</form>
PayPal Form:
<form action="https://www.paypal.com/cgi-bin/webscr" method="post" target="_top">
<input type="hidden" name="cmd" value="_s-xclick">
<input type="hidden" name="hosted_button_id" value="KJU58">
<input type="image" src="http://www.deadlyfishesmods.com/wp-content/uploads/2013/09/Buy-Now-Button.png" border="0" name="submit" alt="PayPal - The safer, easier way to pay online!">
<img alt="" border="0" src="https://www.paypalobjects.com/en_US/i/scr/pixel.gif" width="1" height="1">
</form>
Process-email.php:
<?php
if(isset($_POST['full-name'])) {
require 'includes/PHPMailerAutoload.php';
require 'includes/config.php';
$smtp_host = $config["SMTP_HOST"];
$email = $config["EMAIL"];
$email_password = $config["EMAIL_PASSWORD"];
$email_subject = $config["EMAIL_SUBJECT"];
$name = $_POST['full-name']; // required
$office = $_POST['office']; // required
$mobile = $_POST['mobile']; // required
$user_email = $_POST['email']; // required
$website = $_POST['website']; // required
$card_type = $_POST['body_shots'];
$address_1 = $_POST['shipping_address_1'];
$address_2 = $_POST['shipping_address_2'];
$email_exp = '/^[A-Za-z0-9._%-]+#[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';
function clean_string($string) {
$bad = array("content-type","bcc:","to:","cc:","href");
return str_replace($bad,"",$string);
}
$email_message = "You have a new card order. <br/> <br/>";
$email_message .= "Name: ".clean_string($name)."<br/>";
$email_message .= "Office: ".clean_string($office)."<br/>";
$email_message .= "Mobile Number: ".clean_string($mobile)."<br/>";
$email_message .= "Email: ".clean_string($user_email)."<br/>";
$email_message .= "Website: ".clean_string($website)."<br/>";
$email_message .= "Card Type: ".clean_string($card_type)."<br/>";
$email_message .= "Address: ".clean_string($address_1) . clean_string($address_2) . "<br/>";
$mail = new PHPMailer(); // create a new object
$mail->IsSMTP(); // enable SMTP
$mail->SMTPDebug = 0; // debugging: 1 = errors and messages, 2 = messages only
$mail->SMTPAuth = true; // authentication enabled
$mail->SMTPSecure = 'ssl'; // secure transfer enabled REQUIRED for GMail
$mail->Host = "$smtp_host";
$mail->Port = 465; // or 587
$mail->IsHTML(true);
$mail->Username = "$email";
$mail->Password = "$email_password";
$mail->Subject = "$email_subject";
$mail->Body = $email_message;
$validAttachments = array();
if($card_type !== "Full Shot"){
foreach($_FILES['upload-file']['name'] as $index => $fileName) {
$filePath = $_FILES['upload-file']['tmp_name'][$index];
$validAttachments[] = array($filePath, $fileName);
}
foreach($validAttachments as $attachment) {
$mail->AddAttachment($attachment[0], $attachment[1]);
}
}
$mail->AddAddress("example#sample.com");
if(!$mail->Send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
} else {
$counter = 1;
foreach($validAttachments as $attachment) {
move_uploaded_file( $attachment[0], "uploads/" . clean_string($name) . "_" . $counter . "_" . rand() . "_" . $attachment[1] );
$counter++;
}
}
}
You can have the paypal url as your form's action and use Ajax to save or email the form data before the form is submitted to Paypal. You can also use the Ajax response to prepare the form before submission, e.g. filling some hidden fields
Here's an example:
myform.php:
<form id="myform" method="post" action="<?php echo $paypal_url; ?>">
<input type="text" ...>
<input type="hidden" name="my-hidden-field" id="my-hidden-field" value="this is hidden">
...other form fields...
</form>
saveform.php: Processes the Ajax request and returns a response that can be used to manipulate the form before submission
<?php
if (!empty($_POST)) {
//save $_POST data to the database
//or insert your email code portion here
...
//also, fill some data as response
$response = array('my_hidden_field' => 'this is now filled in');
//next line returns the response
echo json_encode($response);
}
myform.js: Submits form data to saveform.php before submitting to paypal
$j = jQuery.noConflict();
$j(document).ready(function() {
$j('#myform').submit(submit_myform);
});
function submit_myform() {
if (!myform_is_valid()) {
window.location.href = "#myform";
return false;//prevent normal browser submission, to display validation errors
} else {
$j.ajax({
url: 'saveform.php',
type: 'POST',
data: $j(this).serialize(),
dataType:'json', //data type of Ajax response expected from server
success: myform_success //callback to handle Ajax response and submit to Paypal
});
return false;//prevent normal browser submission, since the form is submitted in the callback
}
}
function myform_is_valid() {
$valid = true;
//validate data; if there's a validation error, set $valid=false and display errors on page
...
return $valid;
}
function myform_success(response) {
//this is called whenever the ajax request returns a "200 Ok" http header
//manipulate the form as you wish
$j('#my-hidden-field').val(response.my_hidden_field);
//submit the form (to the form's action attribute, i.e $paypal_url)
document.forms['myform'].submit();
}
Instead of the jquery.ajax call you can also use the shorter:
$j.post('saveform.php',$j('#myform').serialize(),myform_success,"json")
This is to give you an idea of how you can accomplish both in one submit action.
Related
I have this PHP form validator that is also hooked up to a mail function and to keep things organized I did the form validation in a separate function that is being called when the form is submitted.
Now I have this problem that I don't know how to display the error message when a field is empty in the HTML form.
Can anyone help? Thank you in advance.
I'm also pretty new to PHP and the whole thing.
PHP:
<?php
// Validation function
function validation($name, $email, $message) {
// Searching for every empty POST variable
// And if empty push into $error array
if (empty($name)) {
array_push($errors, "Name");
}
if (empty($email)) {
array_push($errors, "E-Mail");
} else if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$mail_error = " and E-Mail must be correct/filled out.";
}
if (empty($message)) {
array_push($errors, "Message");
}
// Combining all index of array to one final string
$final = implode(", ", $errors);
// Adding additional string to final
$final .= " is not allowed to be empty." . $mail_error . "\n";
return $final;
}
if (isset($_POST["submit"])) {
// Defining POST variables for validation and mail content
$fname = $_POST["fname"];
$femail = $_POST["femail"];
$fmessage = $_POST["fmessage"];
// Defining variable for pushing errors for validation
$errors = array();
// Calling function
validation($fname, $femail, $fmessage);
}
HTML:
<form name="main-form" action="" method="post" class="row g-3 pt-1 p-5 bg-custom">
<div class="input-group mb-3 col-md-6">
<span class="input-group-text">Name</span>
<input name="fname" type="text" class="form-control me-3 " placeholder="Name" aria-label="Name">
<span class="input-group-text">E-Mail</span>
<input name="femail" type="email" class="form-control" placeholder="example#mail.com"aria-label="example#mail.com">
</div>
<div class="input-group mb-3 col-md-12 col-sm-6">
<span class="input-group-text">Message</span>
<textarea name="fmessage" type="text" class="form-control"></textarea>
</div>
<!-- The error message if a field is empty should be displayed here: -->
<p id="error-message" class="text-center text-danger"><?php echo($final); ?></p>
<div class="col-md-12 text-center">
<button class="btn btn-primary me-2" id="btn-send" style="width: 30%;" class="btn btn-primary me-2" type="submit" name="submit">Send</button>
</div>
</form>
<?php
// Validation function
function validation($name, $email, $message) {
$errors = [];
$final = "";
// Searching for every empty POST variable
// And if empty push into $error array
if (empty($name)) {
array_push($errors, "Name");
}
if (empty($email)) {
array_push($errors, "E-Mail");
} else if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$mail_error = " and E-Mail must be correct/filled out.";
}
if (empty($message)) {
array_push($errors, "Message");
}
// Combining all index of array to one final string
$final = implode(", ", $errors);
// Adding additional string to final
$final .= " is not allowed to be empty." . $mail_error . "\n";
return $final;
}
if (isset($_POST["submit"])) {
// Defining POST variables for validation and mail content
$fname = $_POST["fname"];
$femail = $_POST["femail"];
$fmessage = $_POST["fmessage"];
// Defining variable for pushing errors for validation
// Calling function
$error = validation($fname, $femail, $fmessage);
}
HTML
<form name="main-form" action="" method="post" class="row g-3 pt-1 p-5 bg-custom">
<div class="input-group mb-3 col-md-6">
<span class="input-group-text">Name</span>
<input name="fname" type="text" class="form-control me-3 " placeholder="Name" aria-label="Name">
<span class="input-group-text">E-Mail</span>
<input name="femail" type="email" class="form-control" placeholder="example#mail.com"aria-label="example#mail.com">
</div>
<div class="input-group mb-3 col-md-12 col-sm-6">
<span class="input-group-text">Message</span>
<textarea name="fmessage" type="text" class="form-control"></textarea>
</div>
<!-- The error message if a field is empty should be displayed here: -->
<p id="error-message" class="text-center text-danger"><?=if(isset($error)); $error : "";?></p>
<div class="col-md-12 text-center">
<button class="btn btn-primary me-2" id="btn-send" style="width: 30%;" class="btn btn-primary me-2" type="submit" name="submit">Send</button>
</div>
</form>
$error = validation($fname, $femail, $fmessage); store data in variable and
isset() use to check variable exist or not
I created an AMP page for my website, all works fine on my desktop browser, tested and works fine on my mobile, if certain fields are empty or not valid, the submit-error correctly displays the error message, also, on successful submission it correctly displays the submit-success message.
When I submitted the page to Google to cache the amp page, I tested the form once again, this time it isn't displaying the error or success messages. But if the form submission is valid, it will send me an email but not display the success message.
Form html code:
<form action-xhr="posts/submit.php" method="POST" class="contactForm" target="_top">
<fieldset>
<div class="formFieldWrap">
<label class="field-title">Select a product:<span>(required)</span></label>
<div class="select-style full-bottom">
<select name="product">
<option selected="" disabled="">Select a Product</option>
<option value="product1">product 1</option>
<option value="product2">product 2</option>
</select>
</div>
</div>
<div class="formFieldWrap">
<label class="field-title">Full Name:<span>(required)</span></label>
<input type="text" name="fullname" value="" class="contactField" />
</div>
<div class="formFieldWrap">
<label class="field-title">Telephone: <span>(required)</span></label>
<input type="text" name="telephone" value="" class="contactField" />
<div class="formFieldWrap">
<label class="field-title">Email: <span>(required)</span>
</label>
<input type="text" name="email" value="" class="contactField" />
</div>
<input type="hidden" name="ps" value="amp_Homepage">
<div class="formSubmitButtonErrorsWrap contactFormButton">
<input type="submit" class="buttonWrap button bg-teal-dark contactSubmitButton" value="Start my claim" />
</div>
</fieldset>
<div submit-success>
<template type="amp-mustache">
<span class="center-text color-green-dark"><strong>Congratulations {{fullname}}!</strong> You have successfully submitted your claim. You can expect a telephone call from My Claim Solved just to confirm a few details.</span>
</template>
</div>
<div submit-error>
<template type="amp-mustache">
<span class="center-text color-red-light"><strong>Oops!</strong> {{message}}</span>
</template>
</div>
</form>
PHP page:
<?php
$source_origin = trim($_REQUEST['__amp_source_origin']);//Security
if($source_origin != "https://example.com"){
echo "Not allowed origin";
return;
}
header('AMP-Access-Control-Allow-Source-Origin: https://example.com');
header('Content-Type: application/json; charset=UTF-8;');
$start = microtime(true);
$con=mysqli_connect("myip","myuser","mypass","mydb");
$Product = mysqli_real_escape_string($con, $_REQUEST['product']);
$FullName = mysqli_real_escape_string($con, $_REQUEST['fullname']);$FullName = ltrim($FullName);$FullNameMail = mysqli_real_escape_string($con, $_REQUEST['fullname']);
$Telephone = mysqli_real_escape_string($con, $_REQUEST['telephone']);
$Email = mysqli_real_escape_string($con, $_REQUEST['email']);
$Provider = mysqli_real_escape_string($con, $_REQUEST['provider']);
$PageSource = mysqli_real_escape_string($con, $_REQUEST['ps']);
if($Product != 'product1' && $Product != 'product2'){
header('Status: 400', TRUE, 400);
echo json_encode(array('message'=>'You must select a product.'));
}elseif(empty($FullName) || strlen($FullName)<3) {
header('Status: 400', TRUE, 400);
echo json_encode(array('message'=>'You must enter your full name.'));
}elseif (empty($Telephone) || strlen($Telephone)<9) {
header('Status: 400', TRUE, 400);
echo json_encode(array('message'=>'You must enter a valid telephone number.'));
}elseif (!filter_var($Email, FILTER_VALIDATE_EMAIL)) {
header('Status: 400', TRUE, 400);
echo json_encode(array('message'=>'You must enter a valid email address.'));
}else{
// Send Email
$To = "myemail#example.com";
$Message = "bla bla";
$Headers = "From: myemail#example.com";
mail($To, 'subject bla', $Message, $Headers);
echo json_encode(array("product"=>$Product,"fullname"=>$FullName,"telephone"=>$Telephone,"email"=>$IPAddress));
}
?>
just to let you know how it was fixed (thanks to ade for pointing me in the right direction), I amended the headers on the php page to the below:
header("access-control-allow-credentials:true");
header("access-control-allow-headers:Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token");
header("access-control-allow-methods:POST, GET, OPTIONS");
header("access-control-allow-origin:".$_SERVER['HTTP_ORIGIN']);
header("access-control-expose-headers:AMP-Access-Control-Allow-Source-Origin");
header("amp-access-control-allow-source-origin:https://".$_SERVER['HTTP_HOST']);
header("Content-Type: application/json");
This question already has answers here:
How to fix "Headers already sent" error in PHP
(11 answers)
Closed 6 years ago.
How can I make my thankyou text appear after form has been successfully sent?
Right now it does reappear in the form part of the page after submission but the Thankyou text doesn't appear, it worked before I put the - header('Location: index.php#contact'); but now it doesnt show up at all. My code is below:
PHP CODE
<?php
if($_POST['submit']){
if(!$_POST['name']){
$error= "<br/>-Please enter your name" ;
}
if(!$_POST['email']){
$error.= "<br/>-Please enter your email" ;
}
if (trim($_POST['message']) == "")
{
$error.= "<br/>-Please enter message";
}
if(!$_POST['contact']!=$match){
$error.= "<br/>-Please enter your contact number" ;
}
if ($error){
$result= "Whoops, error: $error";
}
else{
mail('mahdi.mashrafi#yahoo.com', "Contact message", "Name: ".$_POST['name']." Email: ".$_POST['email']."
Email: ".$_POST['name']."
Message : ".$_POST['message']."
Contact :".$_POST['contact'] );
{
$result= "Thankyou, Ill be in touch shortly";
//to get the stored
session_start()
if(isset($_SESSION["result")){
$result=$_SESSION;
}
$_SESSION["result"]=$result;
header("location:index.php#contact?result=".$result);
$result=$_GET["result"];
}
}
}
?>
HTML & PHP form
<div id="contact" >
<div class="container">
<div class="row wowload fadeInLeftBig ">
<form method = "post" action = "" id = "contact-form " class="center" role ="form">
<!--Contact Starts-->
<div >
<div class="contactform center">
<h2 class="text-center wowload fadeInUp">Tell us about your <span>Project</span></h2><br>
<?php echo $result; ?>
<div class="col-sm-6 hello">
<input type = "text" name = "name" class = "form-control" placeholer = "Your name" value = "<?php echo $_POST['name'];?>" >
</div>
<div class="col-sm-6">
<input type = "email" name = "email" class = "form-control" placeholer = "Your email" value ="<?php echo $_POST['email'];?>">
</div>
<div class="col-sm-12">
<textarea name = "message" rows = "7" class = "form-control" placeholder = "message"><?php echo $_POST['message']; ?> </textarea>
</div>
<div class="col-sm-6">
<input type="text" name="contact" placeholder="Contact" value ="<?php echo $_POST['contact'];?>">
</div>
<div class="col-sm-6">
<input type="text" name="budget" placeholder="Project Budget"></div>`
</div>
<input type = "submit" name = "submit" class = "btn btn-secondary" value = "send message"/>
</div>
</form>
</div>
</div>
</div>
UPDATE
The php code has been updated, im not sure where to place the codes given in the answer as my php knowledge isnt so good.
try this
if(mail(.......))
{
header('Location: index.php?result=Thankyou, Ill be in touch shortly');
exit();
}
index.php
if(isset($_GET['result']))
{
echo $_GET['result'];
}
What happens?
1.You set the variable $result
2.you redirect using header
Whys that wrong?
When you redirect a new php instance is opened. Your variable $result isnt set anymore.
How to solve?
1.Store the $result somewhere ( sessions for example):
//to get the stored
session_start()
if(isset($_SESSION["result")){
$result=$_SESSION;
}
//to store
$_SESSION["result"]=$result;
2.Put it into the url:
header("location:http://url#contact?result=".$result);
//access it
$result=$_GET["result"];
I'm trying to get a form pre-filled using a query string and let the user make any necessary changes then press submit and have the form process and send an email to an administrator for doing whatever it is they need to do with the information.
I'm using PHP to populate the form and I started with a tutorial from NetTuts for the email form processing because it did validation inline. Hopefully validation isn't necessary because all the fields are pre-filled but I wanted to have the form check just to make sure the user doesn't clear a field before submitting the form. I'm at a loss as to why the form won't process correctly.
The only changes between my form and the tutorial are in variable names, the inclusion and some $_GET superglobals to grab the form data from the query string, and the use of echo to fill out the form from the $_GET superglobals instead of the session data should the user submit the form without filling everything out. Everything else has been copied verbatim from the tutorial.
Any help solving this problem, even if it's rethinking how I might go about doing this, would be much appreciated.
Below is the code for the form page and the processing page.
Form Page:
<?php
session_start();
// site root folder
$root_folder = "/meetingplannersignup";
//get values of displayed form fields from URL
$FirstName= $_GET['FirstName'];
$LastName = $_GET['LastName'];
$Organization = $_GET['Organization'];
$EmailAddress = $_GET['EmailAddress'];
$Phone = $_GET['Phone'];
$EventType = $_GET['EventType'];
$EventName = $_GET['EventName'];
$EventLocation = $_GET['EventLocation'];
$HotelName = $_GET['HotelName'];
$EventStart = $_GET['EventStart'];
$EventEnd = $_GET['EventEnd'];
// get values of hidden form fields from URL
$ExtReferenceID = $_GET['ExtReferenceID'];
$City = $_GET['City'];
$State = $_GET['State'];
$ZipCode = $_GET['ZipCode'];
$CountryCode = $_GET['CountryCode'];
?>
<!DOCTYPE html>
<!--[if IE 8]><html class="no-js lt-ie9" lang="en" > <![endif]-->
<!--[if gt IE 8]><!--><html class="no-js" lang="en" > <!--<![endif]-->
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Simplify Event Management with GroupMAX</title>
<link rel="stylesheet" href="<?php echo $root_url ?>/assets/css/bootstrap.css">
</head>
<body>
<div class="container">
<!-- begin main nav -->
<nav class="navbar navbar-static-top navbar-inverse" role="navigation">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-main-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse navbar-main-collapse">
<ul class="nav navbar-nav">
<li class="active">home</li>
<li>fill out form</li>
</ul>
</div><!-- /.navbar-collapse -->
</nav>
<!-- end main nav -->
<div class="row">
<div class="col-lg-12">
<h1>Simplify Event Management with GroupMAX</h1>
<h3>Impress Your Attendees. Optimize Your Event.</h3>
<hr />
</div>
</div>
<div class="row">
<div class="col-lg-6">
<h4>Included Features are:</h4>
<ul>
<li><strong>Event Booking Websites – </strong>Passkey’s award winning booking website allows for personalized hotel reservation website where attendees can make, modify or cancel their hotel bookings directly into that group's contracted block.</li>
<li><strong>Integrated with Event Registration - </strong>RegLink™ is an integration technology that can link any online planner registration solution to Passkey's best-in-class hotel reservation system, allowing meeting planners to integrate hotel reservations directly into their event registration process.</li>
<li><strong>Event Dashboard – </strong>With Event Dashboard Planners can track their events, manage their lists and monitor reservations anytime online. With Passkey’s LiveView Dashboards, meeting planners can get an instant snapshot of their event in a fun, interactive environment. </li>
<li><strong>SmartAlerts™ - </strong>Automatic e-mails containing vital event information that are automatically sent out to a list of recipients at specific intervals or critical event milestones.</li>
</ul>
</div>
<div class="col-lg-6">
<div class="row">
<div class="col-lg-12">
<!-- begin error processing -->
<div class="well">
<?php
//init variables
$cf = array();
$sr = false;
if(isset($_SESSION['cf_returndata'])){
$cf = $_SESSION['cf_returndata'];
$sr = true;
}
?>
<div id="errors" class="alert alert-danger<?php echo ($sr && !$cf['form_ok']) ? ' show_alert' : ''; ?>">
<p>There were some problems with your form submission:</p>
<ul>
<?php
if(isset($cf['errors']) && count($cf['errors']) > 0) :
foreach($cf['errors'] as $error) :
?>
<li><?php echo $error ?></li>
<?php
endforeach;
endif;
?>
<?php
//init variables
$cf = array();
$sr = false;
if(isset($_SESSION['cf_returndata'])){
$cf = $_SESSION['cf_returndata'];
$sr = true;
}
?>
</ul>
</div>
<p id="success" class="alert alert-success<?php echo ($sr && $cf['form_ok']) ? ' show_alert' : ''; ?>">Thanks for your message! We will get back to you ASAP!</p>
<!-- end error processing -->
<!-- begin form -->
<fieldset>
<legend>Your Information</legend>
<p>Please review the pre-filled information and correct any inaccurate information prior to submitting the form.</p>
<form method="post" action="process.php">
<div class="form-group">
<label>First Name</label>
<input type="text" class="form-control" id="FirstName" value="<?php echo ($sr && !$cf['form_ok']) ? $cf['posted_form_data']['FirstName'] : '' ?><?php echo $FirstName; ?>">
</div>
<div class="form-group">
<label>Last Name</label>
<input type="text" class="form-control" id="LastName" value="<?php echo $LastName; ?>">
</div>
<div class="form-group">
<label>Company/Organization</label>
<input type="text" class="form-control" id="Organization" value="<?php echo $Organization; ?>">
</div>
<div class="form-group">
<label>Email Address</label>
<input type="text" class="form-control" id="EmailAddress" value="<?php echo $EmailAddress; ?>">
</div>
<div class="form-group">
<label>Phone Number</label>
<input type="text" class="form-control" id="Phone" value="<?php echo $Phone; ?>">
</div>
<div class="form-group">
<label>Event Type</label>
<input type="text" class="form-control" id="EventType" value="<?php echo $EventType; ?>">
</div>
<div class="form-group">
<label>Event Name</label>
<input type="text" class="form-control" id="EventName" value="<?php echo $EventName; ?>">
</div>
<div class="form-group">
<label>Event Location</label>
<input type="text" class="form-control" id="EventLocation" value="<?php echo $EventLocation; ?>">
</div>
<div class="form-group">
<label>Hotel Name</label>
<input type="text" class="form-control" id="HotelName" value="<?php echo $HotelName; ?>">
</div>
<div class="form-group">
<label>Start/Arrival Date</label>
<input type="text" class="form-control" id="EventStart" value="<?php echo $EventStart; ?>">
</div>
<div class="form-group">
<label>End Date</label>
<input type="text" class="form-control" id="EventEnd" value="<?php echo $EventEnd; ?>">
</div>
<hr />
<input type="submit" value="Submit" class="btn btn-primary" />
<!--hidden fields-->
<input type="hidden" id="ExtReferenceID" value="<?php echo $ExtReferenceID; ?>">
<input type="hidden" id="City" value="<?php echo $City; ?>">
<input type="hidden" id="State" value="<?php echo $State; ?>">
<input type="hidden" id="ZipCode" value="<?php echo $ZipCode; ?>">
<input type="hidden" id="CountryCode" value="<?php echo $CountryCode; ?>">
</form>
<?php unset($_SESSION['cf_returndata']); ?>
</fieldset>
</div>
<!-- end form -->
</div>
</div>
</div>
</div>
</div>
</body>
</html>
Processing Page:
<?php
if( isset($_POST) ){
//form validation vars
$formok = true;
$errors = array();
//submission data
$ipaddress = $_SERVER['REMOTE_ADDR'];
$date = date('d/m/Y');
$time = date('H:i:s');
//form data
$FirstName = $_POST['FirstName'];
$LastName = $_POST['LastName'];
$Organization = $_POST['Organization'];
$EmailAddress = $_POST['EmailAddress'];
$Phone = $_POST['Phone'];
$EventType = $_POST['EventType'];
$EventName = $_POST['EventName'];
$EventLocation = $_POST['EventLocation'];
$HotelName = $_POST['HotelName'];
$EventStart = $_POST['EventStart'];
$EventEnd = $_POST['EventEnd'];
// hidden form fields
$ExtReferenceID = $_POST['ExtReferenceID'];
$City = $_POST['City'];
$State = $_POST['State'];
$ZipCode = $_POST['ZipCode'];
$CountryCode = $_POST['CountryCode'];
//validate form data
//validate First Name is not empty
if(empty($FirstName)){
$formok = false;
$errors[] = "You have not entered a First Name";
//validate Last Name is not empty
} elseif (empty($LastName)){
$formok = false;
$errors[] = "You have not entered a Last Name";
//validate Company/Organization is not empty
} elseif (empty($Organization)){
$formok = false;
$errors[] = "You have not entered a Company or organization";
//validate email address is not empty
} elseif (empty($EmailAddress)){
$formok = false;
$errors[] = "You have not entered an email address";
//validate email address is valid
} elseif (!filter_var($EmailAddress, FILTER_VALIDATE_EMAIL)){
$formok = false;
$errors[] = "You have not entered a valid Email Address";
//validate Last Name is not empty
} elseif (empty($Phone)){
$formok = false;
$errors[] = "You have not entered a Phone Number";
//validate Last Name is not empty
} elseif (empty($EventType)){
$formok = false;
$errors[] = "You have not entered an Event Type";
//validate Last Name is not empty
} elseif (empty($EventName)){
$formok = false;
$errors[] = "You have not entered an Event Name";
//validate Last Name is not empty
} elseif (empty($EventLocation)){
$formok = false;
$errors[] = "You have not entered an Event Location";
//validate Last Name is not empty
} elseif (empty($HotelName)){
$formok = false;
$errors[] = "You have not entered a Hotel Name";
//validate Last Name is not empty
} elseif (empty($EventStart)){
$formok = false;
$errors[] = "You have not entered an Event Start Date";
//validate Last Name is not empty
} elseif (empty($EventEnd)){
$formok = false;
$errors[] = "You have not entered an Event End Date";
}
//send email if all is ok
if($formok){
$headers = "From: meetingplannersignup#passkey.com" . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$emailbody = "<p>You have recieved a new meeting planner signup registration:</p>
<p><strong>First Name: </strong> {$FirstName}</p>
<p><strong>Last Name: </strong> {$LastName}</p>
<p><strong>Company/Organization: </strong> {$Organization}</p>
<p><strong>Email Address: </strong> {$EmailAddress}</p>
<p><strong>Phone: </strong> {$Phone}</p>
<hr />
<p><strong>Event Type: </strong> {$EventType}</p>
<p><strong>Event Name: </strong> {$EventName}</p>
<p><strong>Event Location: </strong> {$EventLocation}</p>
<p><strong>Hotel Name: </strong> {$HotelName}</p>
<p><strong>Event Start Date: </strong> {$EventStart}</p>
<p><strong>Event End Date: </strong> {$EventEnd}</p>
<hr />
<p><strong>Reference ID: </strong> {$ExtReferenceID}</p>
<p><strong>City: </strong> {$City}</p>
<p><strong>State: </strong> {$State}</p>
<p><strong>Zip Code: </strong> {$ZipCode}</p>
<p><strong>Country Code: </strong> {$CountryCode}</p>
<hr />
<p>This message was sent from the IP Address: {$ipaddress} on {$date} at {$time}</p> ";
mail("stuart#monderer.com","Meeting Planner Signup",$emailbody,$headers);
}
//what we need to return back to our form
$returndata = array(
'posted_form_data' => array(
'FirstName' => $FirstName,
'LastName' => $LastName,
'EmailAddress' => $EmailAddress,
'Organization' => $Organization,
'Phone' => $Phone,
'EventType' => $EventType,
'EventName' => $EventName,
'EventLocation' => $EventLocation,
'HotelName' => $HotelName,
'EventStart' => $EventStart,
'EventEnd' => $EventEnd,
'ExtReferenceID' => $ExtReferenceID,
'City' => $City,
'State' => $State,
'ZipCode' => $ZipCode,
'CountryCode' => $CountryCode
),
'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']);
}
}
Several problems:
1. isset($_POST) will always be true
In your processing page you check for:
if( isset($_POST) )
This will always evaluate to true even if $_POST is empty. You should check for a specific field to try and guess is the form was submitted
2. You use id instead of name
The form values that are sent via POST are identified via their name, not via their id. In the HTML you can keep the id attribute but for each field that is to be POSTed you must add a name attribute:
<input type="text" class="form-control" name="LastName" id="LastName" value="<?php echo $LastName; ?>">
$_POST['LastName'] is empty if you only identify your form control with an id.
I haven't checked the rest but you should try to fix those points first.
I've successfully created a contact form with php that gives the various required messages. Now I would like to add a simple random arithmetic captcha (non-image). See the anonymised (working) html form and existing (working, but without arithmetic captcha) php below.
The idea is to show "Incorrect answer" in the same way as the other error messages, or to pass to the Thankyou page for a correctly filled out form with correct answer. I've had a good go at this but can't quite get it to work. Any assistance much appreciated.
HTML:
<p>Area of interest:
<input type="radio" name="likeit" value="A" checked="checked" /> A
<input type="radio" name="likeit" value="B" /> B
<input type="radio" name="likeit" value="C" /> C</p>
<p>How did you hear about us?
<select name="how">
<option value=""> -- Please select -- </option>
<option>Recommendation</option>
<option>Internet</option>
<option>Advertisement</option>
<option>Other</option>
</select></p>
<p><strong>Your message subject:</strong><br /><input type="text" name="subject" size="35"/></p>
<p><strong>Your message:</strong><br />
<textarea name="comments" rows="10" cols="40"></textarea></p>
<p>Please answer the following arithmetic question: What is <?php echo $digit1;?> + <?php echo $digit2;?>?
<input name="captcha" type="text" size="2" id="captcha"/></p>
<p><input type="submit" value="Send" /></p>
</form>
PHP:
<?php
/* Contact form with arithmetic captcha */
$myemail = "enquiries#X.co.uk";
/* Check all form inputs using check_input function */
$yourname = check_input($_POST['yourname'], "Enter your name");
$email = check_input($_POST['email']);
$telephone = check_input($_POST['telephone']);
$website = check_input($_POST['website']);
$likeit = check_input($_POST['likeit']);
$how_find = check_input($_POST['how']);
$subject = check_input($_POST['subject'], "Add a subject");
$comments = check_input($_POST['comments'], "Add your message");
/* If e-mail is not valid show error message */
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/", $email))
{
show_error("Email address is not valid");
}
/* If URL is not valid set $website to empty */
if (!preg_match("/^(https?:\/\/+[\w\-]+\.[\w\-]+)/i", $website))
{
$website = '';
}
/* Message for the email */
$message = "Hello!
Your contact form has been submitted by:
Name: $yourname
Email: $email
Telephone: $telephone
URL: $website
Area of interest? $likeit
How did they find us? $how_find
Comments:
$comments
End of message
";
/* Send the message using mail() function */
mail($myemail, $subject, $message);
/* Redirect visitor to the thankyou page */
header('Location: thankyou.html');
exit();
/* Functions used */
function check_input($data, $problem='')
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
if ($problem && strlen($data) == 0)
{
show_error($problem);
}
return $data;
}
function show_error($myError)
{
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<!--
Head data in here
-->
<html xmlns="http://www.w3.org/1999/xhtml">
<body>
<div id="mainheader">
<div id="mainlogo">
<h1><a href="http://www.X.co.uk/" title="X">
<img style="border:0;width: 260px; height: 160px;" src="images/X.jpg" alt="X" /></a></h1>
</div>
</div>
<div id="content">
<div class="content">
<h2 class="title">Error!</h2>
<p><strong>Please correct the following error:</strong></p>
<p><?php echo $myError; ?></p>
</div>
</div>
<div id="panel">
<div id="main" class="boxed">
<h2 class="heading">Main</h2>
<ul>
<li>Home </li>
<li>About </li>
<li>Contact </li>
</ul>
</div>
<div id="services" class="boxed">
<h2 class="heading">Services</h2>
<ul>
<li>Services </li>
<li>Recent projects </li>
</ul>
</div>
<div id="pricing" class="boxed">
<h2 class="heading">Pricing</h2>
<ul>
<li>Pricing </li>
</ul>
</div>
<div id="info" class="boxed">
<h2 class="heading">Info</h2>
<ul>
<li>Tips and tricks </li>
<li>Useful links </li>
<li>Frequently asked questions </li>
<li>Site map </li>
</ul>
</div>
<div id="contact" class="boxed">
<h2 class="heading">Contact</h2>
<ul>
<li>Contact by email </li>
<li><strong>Telephone:<br />X</strong> </li>
</ul>
</div>
</div>
<div id="mainfooter">
<p> © 2011 X<br />Designed by <strong>X</strong> </p>
<a href="http://validator.w3.org/check?uri=referer" title="Valid XHTML 1.0">
<img style="border:0;width:88px;height:31px" src="images/valid-xhtml10.png" alt="Valid XHTML 1.0" />
</a>
<a href="http://jigsaw.w3.org/css-validator/check/referer" title="Valid CSS!">
<img style="border:0;width:88px;height:31px" src="images/vcss.gif" alt="Valid CSS!" />
</a>
</div>
</body>
</html>
<?php
exit();
}
?>
Generally, the idea of captcha is to prevent automated form processing. Any non-image comparisons will be easily solved.
Regardless, I would use sessions to solve this issue.
Simply store the expected result in a session variable on the first page, and make sure it matches on the second
page1.php:
<?php
session_start();
$digit1 = mt_rand(1,20);
$digit2 = mt_rand(1,20);
if( mt_rand(0,1) === 1 ) {
$math = "$digit1 + $digit2";
$_SESSION['answer'] = $digit1 + $digit2;
} else {
$math = "$digit1 - $digit2";
$_SESSION['answer'] = $digit1 - $digit2;
}
?>
<form method="POST" action="page2.php">
What's <?php echo $math; ?> = <input name="answer" type="text" /><br />
<input type="submit" />
</form>
page2.php
session_start();
echo "You entered ".htmlentities($_POST['answer'])." which is ";
if ($_SESSION['answer'] == $_POST['answer'] )
echo 'correct';
else
echo 'wrong. We expected '.$_SESSION['answer'];
?>
Use a Simple PHP Math Captcha
https://github.com/kmlpandey77/MathCaptcha
MathCaptcha
A Simple PHP Math Captcha
Usage
composer require kmlpandey77/math-captcha
Math in Image
It will return Math in image
Create captcha.php
<?php
require_once 'vendor/autoload.php'; // link to vendor's autoload.php
use Kmlpandey77\MathCaptcha\Captcha;
$captcha = new Captcha();
$captcha->image();
Create form.php
<form action="check.php" method="post">
<p>
Answer it <img src="./captcha.php" alt="" valign="middle"> <input type="text" name="captcha">
</p>
<p><button type="submit" name="submit">Submit</button></p>
</form>
Math in Text
It will return Math in text
Create form.php
Place this code to top of form.php
<?php
require_once 'vendor/autoload.php'; // link to vendor's autoload.php
use Kmlpandey77\MathCaptcha\Captcha;
?>
And place this code in body
<form action="check.php" method="post">
<p>
Answer it <?php echo new Captcha; ?> <input type="text" name="captcha">
</p>
<p><button type="submit" name="submit">Submit</button></p>
</form>
Check
Checks to see if the user entered the correct captcha key
Create check.php
<?php
require_once 'vendor/autoload.php'; // link to vendor's autoload.php
use Kmlpandey77\MathCaptcha\Captcha;
if(isset($_POST['submit'])){
if(Captcha::check()){
//valid action
echo('<font color="green">Answer is valid</font>');
}else{
echo('<font color="red">Answer is invalid</font>');
}
}