Web form - bots getting past all checks when human cant.? - ajax

I have the following code, pretty standard - but it seems that the bots get by without even entering anything into the input fields! where as a normal person cannot since it checks upon submit, so I keep just getting empty emails.
Here is my code, if anyone has any ideas:
the javascript:
$('form.ajax').on('submit', function () {
if($(".field-b").val()) {
return false;
}
var that = $(this),
url = that.attr('action'),
type = that.attr('method'),
data = {};
that.find('[name]').each(function(index, value) {
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
});
for(var property in data) {
if(data.hasOwnProperty(property)) {
if(data[property] == "") {
$('[name="' + property + '"]').parent().addClass("error");
return false;
}
}
}
$.ajax({
url: url,
type: type,
data: data,
success: function(response) {
$(".info,.ajax").hide();
$(".success-send").fadeIn(300);
return false;
}
});
return false;
});
The HTML:
<form class="ajax" action="../email.php" method="post"autocomplete="off">
<div class="form-field">
<input name="form_name" type="text" class="form-field-name">
<label>Your Name</label>
<div class="field-icon-name"></div>
</div>
<div class="form-field">
<input name="form_business" type="text" class="form-field-business">
<label>Business</label>
<div class="field-icon-business"></div>
</div>
<div class="form-field">
<input name="form_email" type="email" class="form-field-email">
<label>Email Address</label>
<div class="field-icon-email"></div>
</div>
<div class="form-field">
<input name="form_phone" type="text" class="form-field-phone">
<label>Phone #</label>
<div class="field-icon-phone"></div>
</div>
<div class="form-field special">
<input name="form_b" type="text" class="form-field-b">
<label>question</label>
</div>
<div class="form-field">
<textarea name="form_message"></textarea>
<label>Message</label>
<div class="field-icon-message"></div>
</div>
<button type="submit">Send Message</button>
</form>
And finally the PHP.
<?php
session_start();
$to = "myemail#domain.com";
$name = $_POST['form_name'];
$phone = $_POST['form_phone'];
$email = $_POST['form_email'];
$business = $_POST['form_business'];
$email = $_POST['form_email'];
$subject = 'Contact Form mattscorner';
$message = 'Name:'.$name.'\n Email + phone:'.$email.", ".$phone."\n Business: ".$business."\n\n".$message;
$headers = "From: $email\n";
$headers .= "MIME-Version: 1.0\n";
$headers .= "Content-type: text/html; charset=iso-8859-1\n";
mail($to, $subject, $message, $headers);
if (mail($to, $subject, $message, $headers)) echo "mail sent"; else echo "mail NOT sent";
?>
It's pretty standard code I think, but I just cant seem to get the bots to even get blocked by the field requirements.
I literally get emails that are just:
Name:\n Email + phone:, Business:

There's a fundamental misunderstanding here. Bots don't run JavaScript, so none of that matters, and you're not doing the same validations on the server side, so they have no trouble getting by. Implement your validations in PHP too.
Also, you really need to do more validation for security anyway - your script is open to all kinds of vulnerabilities, and you're building malformed, non-compliant messages.
I suggest you use an email library such as PHPMailer, which you tagged this question with.

Related

How to fix AJAX modal form in Laravel 5.3

I've upgraded my app from Laravel 4.2 to Laravel 5.3. On an index page listing citations, I have an AJAX modal form to edit or view the login credentials for the citation. This was working fine in Laravel 4.2, but I cannot for the life of me get it to work in 5.3. After about 5 hours Googling and trying different things, I thought I would post it here so that someone way more experienced than me can point me in the right direction.
Here's the link on the index page:
<a style="cursor: pointer; " title= "Login Credentials" data-loopback="cit-pg-1" data-citationid="1079" class="getCitationdetails"><span class="glyphicon glyphicon-lock " title="Login Credentials"></span></a>
And here's the JavaScript:
<script type="text/javascript">
$(document).on('click','.getCitationdetails',function(){
var citationid = $(this).data('citationid');
var loopback = $(this).data('loopback');
$.ajax({
url : '/citation-password',
type:'post',
data : {citationid :citationid, loopback :loopback},
success:function(resp){
$('#AppendLoginDetails').html(resp);
$('#LoginCredentialsModal').modal('show');
$('.loadingDiv').hide();
},
error:function(){
alert('Error');
}
})
})
Here's my route:
Route::match(['get', 'post'], '/citation-password', 'CitationsController#citationpassword');
And here's the Controller method that generates the form on get and saves the data on post:
public function citationpassword()
{
if (Request::ajax()) {
$data = Request::all();
if (!$data['citationid']) {
return redirect('/citations')
->with('flash-danger', 'Missing citation id for Login credentials form!!');
}
// Save loopback variable if we have it in order to return user to the page where they came from; default return location is citations
$loopback = 'citations';
if (array_key_exists("loopback", $data)) {
$loopback = $data['loopback'];
}
$getcitationdetails = Citation::where('id', $data['citationid'])->select('id', 'site_id', 'username', 'password', 'login_email', 'login_notes')->first();
$getcitationdetails = json_decode(json_encode($getcitationdetails), true);
$getsitedetails = Site::where('id', $getcitationdetails['site_id'])->select(
'id',
'directory_username',
'directory_password',
'security_questions',
'email_account',
'email_account_password',
'email_account_name',
'google_user',
'google_pwd',
'name_of_google_account'
)->first();
$getsitedetails = json_decode(json_encode($getsitedetails), true);
$response ="";
$response .= '<form action="'.url('/citation-password').'" method="post">
<div class="modal-body">';
if (!empty($getsitedetails['directory_username'])) {
$response .= '<div class="form-group">
<label for="recipient-name" class="col-form-label">Default login credentials for this site:</label>
<p>Username: '.$getsitedetails['directory_username'].'
<br />Password: '.$getsitedetails['directory_password'].'
<br />Email account: '.$getsitedetails['email_account'].'
<br />Email password: '.$getsitedetails['email_account_password'].'
<br />Name on email account: '.$getsitedetails['email_account_name'].'
<br />Default security questions: '.$getsitedetails['security_questions'].'</p>
<p>Gmail account: '.$getsitedetails['google_user'].'
<br />Gmail password: '.$getsitedetails['google_pwd'].'
<br />Name on Gmail account: '.$getsitedetails['name_of_google_account'].'</p>
</div>';
}
$response .= '
<input type="hidden" name="_token" value="'.csrf_token() .'" />
<input type="hidden" name="citation_id" value="'.$data['citationid'].'" />
<input type="hidden" name="loopback" value="'.$loopback.'" />
<div class="form-group">
<label for="recipient-name" class="col-form-label">Username:</label>
<input type="text" class="form-control" name="username" value="'.$getcitationdetails['username'].'" autocomplete="off">
</div>
<div class="form-group">
<label for="message-text" class="col-form-label">Password:</label>
<input type="text" class="form-control" name="password" value="'.$getcitationdetails['password'].'" autocomplete="off">
</div>
<div class="form-group">
<label for="message-text" class="col-form-label">Login email used:</label>
<input type="text" class="form-control" name="login_email" value="'.$getcitationdetails['login_email'].'" autocomplete="off">
</div>
<div class="form-group">
<label for="message-text" class="col-form-label">Login notes:</label>
<textarea class="form-control" style="height:130px;" name="login_notes">'.$getcitationdetails['login_notes'].'</textarea>
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-success" id="success">Save</button>
<button type="button" class="btn btn-danger" data-dismiss="modal" aria-hidden="true">Cancel</button>
</div>
</form>';
return $response;
} else {
// The popup modal has posted back here; process the data
$data = Request::all();
// Handle & translate loopback; returning user to the page where they came from
$loopback = 'citations';
if ($data['loopback']) {
$loopback = $data['loopback'];
// Translate pages it came from
$trackLoopback = new trackLoopback();
$loopback = $trackLoopback->translate($loopback);
}
$updatecitation = Citation::find($data['citation_id']);
$updatecitation->username = $data['username'];
$updatecitation->password = $data['password'];
$updatecitation->save();
return redirect($loopback)
->with('flash-success', 'Login credentials have been updated successfully!');
}
}
In an effort to isolate the error, I even simplified the form in the controller like this:
public function citationpassword()
{
if (Request::ajax()) {
return '<p>This is the modal form!</p>';
} else {
// The popup modal has posted back here; process the data
$data = Request::all();
// Handle & translate loopback; returning user to the page where they came from
$loopback = 'citations';
if ($data['loopback']) {
$loopback = $data['loopback'];
// Translate pages it came from
$trackLoopback = new trackLoopback();
$loopback = $trackLoopback->translate($loopback);
}
$updatecitation = Citation::find($data['citation_id']);
$updatecitation->username = $data['username'];
$updatecitation->password = $data['password'];
$updatecitation->save();
return redirect($loopback)
->with('flash-success', 'Login credentials have been updated successfully!');
}
}
and also simplified the route to this:
Route::get('/citation-password', 'CitationsController#citationpassword');
but all I get when I click the link is a popup notice, "Error."
I'm not experienced with AJAX. How do I get the form to display in Laravel 5.3?
And/or, how can I change the JavaScript function so that it shows the actual error instead of the "Error" notice? (I tried a number of methods I found on StackOverflow to display errors but all of them resulted in NO error notice; just a blank page. And, I've not been successful at getting my Firefox debugger to show the errors either.)
Thanks!
The correct way to debug the JavaScript is to post the errors this way:
<script type="text/javascript">
$(document).on('click','.getCitationdetails',function(){
var citationid = $(this).data('citationid');
var loopback = $(this).data('loopback');
$.ajax({
url : '/citation-password',
type:'post',
data : {citationid :citationid, loopback :loopback},
success:function(resp){
$('#AppendLoginDetails').html(resp);
$('#LoginCredentialsModal').modal('show');
$('.loadingDiv').hide();
},
error: function(xhr, ajaxOptions, thrownError) {
alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
}
})
})
Once you do so, you will see that the error has to do with missing CsrfToken for the form. [The actual error message is from the Laravel framework: Illuminate\Session\TokenMismatchException: in file /home/reviewsites/moxy53/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/VerifyCsrfToken.php on line 6] Since both the get and post verbs use the same route, Laravel is requiring the CsrfToken before the form with the Csrf field gets generated.
It is possible (but NOT recommended!) to exclude this route from CSRF protection by editing App\Http\Middleware\VerifyCsrfToken.php with the following exception:
/**
* The URIs that should be excluded from CSRF verification.
*
* #var array
*/
protected $except = [
'/citation-password',
];
However, a much better approach is to add the token. It is correct that since you are using a post method to send the data values to the controller, you cannot use the controller to generate the token field in the form. Hence, the solution is to take the html out of the controller and put it in the blade. These lines:
$response .= '<form action="'.url('/citation-password').'" method="post">
<div class="modal-body">';
...
</div>
</form>';
should not be in the $response generated by the controller, but should instead be in the modal div in the blade itself. THEN, you can add the CSRF field in the blade thus:
<form action="{{url('/citation-password')}}" method="post">
{{ csrf_field() }}
<div class="modal-body" id="AppendLoginDetails">
</div>
</form>

Ajax and PHP specialchars issues

When i send a form contains data from inputs without specialchars, it reaches the PHP file and get set in DB in ease.
Also when selecting, there are no problems at all.
But, when user types the next keys, the thing is different:
" or ' or <script> or alert('yes'); or \ or $ and so for and so on.
What i've tried:
Using tons of encodeURI or encodeURIComponent functions or JSON.stringify
or escapeHTML and what i didn't try..
but nothing works.
the most problematic is: <script> or alert('yes');
which are not only that not being sent to the PHP file, they stuck the whole page!
notice: now ive noticed that even here in stackoveflow, when i write <script> tag not in a code brackets, stackoverflow displays just nothing!
now, some strings, somehow, finally get delivered to the php file,
but i also have the continious problem when im trying to store them:
they are in json encoded, so i wont do each object key some long and time consuming functions like htmlspecialchars / mysqli_real_escape_string /
htmlentities or others.. it will be very uncomfortable to work like this....
an example of the html/php first page:
<div class="contact-form">
<form ng-submit="processForm()" class="default-form">
<div class="row">
<div class="col-lg-3">
<label for="">* שם פרטי ושם משפחה</label>
<input type="text" required ng-model="formData.full_name" placeholder="* שם פרטי ושם משפחה">
</div>
<div class="col-lg-3">
<label for="">* כתובת דוא׳׳ל</label>
<input type="text" required ng-model="formData.email" placeholder="* כתובת דוא׳׳ל">
</div>
<div class="col-lg-3">
<label for="">* טלפון</label>
<input type="text" required ng-model="formData.phone" placeholder="* טלפון">
</div>
<div class="col-lg-3">
<label for="">* סוג קבלן</label>
<select required ng-model="formData.type">
<option value="">* סוג קבלן</option>
<option value="פרטי" alt="">פרטי</option>
<option value="יזם" alt="">יזם</option>
<option value="בנייה ציבורית" alt="">בנייה ציבורית</option>
</select>
</div>
<div class="col-lg-12">
<label for="">
העלאת קבצים
</label>
<input type="file" ng-file-model="formData.files" name="files" multiple style="margin-top:15px">
</div>
<div class="col-lg-12" style="margin-top:40px">
<input type="checkbox" ng-model="formData.newsletter" id="newsletter" >
<label for="newsletter">קבל מבצעים ועדכונים במייל</label>
</div>
<div class="col-lg-12" style="margin-top:10px">
<button class="thm-btn bg-clr1" style="color:white; font-weight:bold" type="submit">לשליחה לחץ כאן</button>
<h3 class="loader" style="display:none">טוען ומעלה קבצים...</h3>
</div>
</div>
</form>
as you can see, just another angular based form.
now the JS file:
$scope.formData = {
full_name: "raz",
phone: "0509921014",
email: "razwebs#gmail.com",
type: "בנייה ציבורית",
newsletter: true,
files: "",
};
$scope.processForm = function() {
$(".bg-clr1").hide();
$(".loader").show();
var data = new FormData();
if ($scope.formData.files.length>0)
{
var files = $scope.formData.files;
for (var k=0; k<files.length; k++)
data.append("file-"+k, files[k]);
}
var formData = JSON.stringify($scope.formData);
formData = encodeURIComponent(formData);
$.ajax({
type: 'POST',
url: 'send_quote.php?formData=' + formData,
cache: false,
contentType: false,
processData: false,
data: data,
success: function(response) {
console.log(response);
$(".bg-clr1").show();
$(".loader").hide();
//window.location = "thanks.php";
}
});
};
note that in this js file, im also sending post and get, which post is the FormData object contains files, and the get contains the regular strings.
and finally the php page:
$array = $_FILES;
$files = [];
for ($i=0; $i<count($array); $i++)
{
$file = $_FILES["file-" . $i];
$name = $file["name"];
$fileType = $file["type"];
$tmp_name = $file["tmp_name"];
$ext = pathinfo($name, PATHINFO_EXTENSION);
$ext = strtolower($ext);
$fileId = rand(1,10000000);
$dir = "admin/uploads/";
$randName = $dir . $fileId . "." . $ext;
move_uploaded_file($tmp_name, $randName);
array_push($files, $randName);
}
$formData = urldecode($_GET['formData']);
$fd = json_decode($formData, true);
$fd["files"] = $files;
$fd = json_encode($fd, JSON_UNESCAPED_UNICODE);
$theDate = time();
mysqli_query($con, "INSERT INTO quotes
(
`quote`,
`status`,
`date`
)
VALUES
(
'$fd',
0,
'$theDate'
)
");
hope it seems clear, i really spent tons of hours to solve this issue,
nothing works, its really frustrated and i sure others facing the same issue as well...
if someone can help, it will be awesome, and sorry for medium level english.
thanks!

Run PHP function without reloading doesnt work with AJAX

I know this question has been asked a lot, but I can't solve my problem.
I want to run the PHP function without reloading the page. Why does this not work? The php file is indexTest.php.
The page is just scrolling to the top and nothing works.
I am new to AJAX so I really dont know what to do.
HTML:
<script type="text/javascript">
function submitdata()
{
var nameForm=document.getElementById( "nameForm" );
var emailForm=document.getElementById( "emailForm" );
var messageForm=document.getElementById( "messageForm" );
$.ajax({
type: 'post',
url: 'indexTest.php',
data: {
name:nameForm,
email:emailForm,
message:messageForm
},
});
return false;
}
</script>
<form onsubmit="return submitdata()" method="POST" id="contactForm">
<input spellcheck="false" class="first" type="text" name="name" placeholder="name" id="nameForm">
<input spellcheck="false" class="first" type="text" name="email" placeholder="email" id="emailForm">
<textarea rows="8" spellcheck="false" class="last" type="text" name="message" placeholder="message" id="messageForm"></textarea>
<input type="submit" name="submit" value="" id="button">
</form>
PHP:
<?php
if(isset($_POST['submit'])){
$to = "*"; // this is your Email address
$from = $_POST['email']; // this is the sender's Email address
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "Invalid email format";
};
$first_name = $_POST['name'];
$subject = "Form submission";
$subject2 = "Copy of your form submission";
$message = "Email from: " . $from . "\n\n" . $first_name . " wrote the following:" . "\n\n" . $_POST['message'];
$message2 = "Here is a copy of your message " . $first_name . "\n\n" . $_POST['message'];
$headers = "From:" . $from;
$headers2 = "From:" . $to;
mail($to,$subject,$message,$headers);
mail($from,$subject2,$message2,$headers2); // sends a copy of the message to the sender
echo '<script language="javascript">';
echo 'alert("message successfully sent")';
echo '</script>';
// You can also use header('Location: thank_you.php'); to redirect to another page.
}
?>
The problem is that you are posting through the form itself, when you actually want to post through AJAX. Essentially, because you are calling your JavaScript function in onsubmit, the JavaScript will get run in addition to the default form submission.
What you need to do is disable default form submission with e.preventDefault();, and then run your JavaScript instead:
$("#contactForm").submit(function(e) {
e.preventDefault();
submitdata();
});
Hope this helps! :)

How to use cashier package in laravel 5.2?

I am creating a user subscription plan, For this I am using cashier package in laravel 5.2. I am following the exact way in provided in the tutorial given in laravel document https://laravel.com/docs/5.2/billing. But I am getting the error
ErrorException in FacebookScraperController.php line 1767:
Undefined variable: creditCardToken
my controller code:
$user = User::find(2);
$res = $user->newSubscription('main', 'monthly')->create($creditCardToken);
dd($res);
What should I pass the value inside the $creditCardToken variable.
I tried to give the card details inside this variable. But getting error.
Please help me out.
You will need to pass the subscription plan here with the token generated at the time of card entry.
Here is the step you can follow.
create a view page:
<form action="/subscription" method="POST" id="payment-form">
<span class="payment-errors"></span>
<div class="form-row">
<label>
<span>Card Number</span>
<input type="text" size="20" data-stripe="number">
</label>
</div>
<div class="form-row">
<label>
<span>Expiration (MM/YY)</span>
<input type="text" size="2" data-stripe="exp_month">
</label>
<span> / </span>
<input type="text" size="2" data-stripe="exp_year">
</div>
<div class="form-row">
<label>
<span>CVC</span>
<input type="text" size="4" data-stripe="cvc">
</label>
</div>
<input type="submit" class="submit" value="Submit Payment">
</form>
<script src="//code.jquery.com/jquery-1.9.1.js"></script>
<script src="//ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.min.js"></script>
<script type="text/javascript" src="https://js.stripe.com/v2/"></script>
<script type="text/javascript">
Stripe.setPublishableKey('pk_test_TSGgkchoa9iQU4ZQ628a8Auz');
</script>
<script>
$(function() {
var $form = $('#payment-form');
$form.submit(function(event) {
// Disable the submit button to prevent repeated clicks:
$form.find('.submit').prop('disabled', true);
// Request a token from Stripe:
Stripe.card.createToken($form, stripeResponseHandler);
// Prevent the form from being submitted:
return false;
});
});
function stripeResponseHandler(status, response) {
// Grab the form:
var $form = $('#payment-form');
if (response.error) { // Problem!
// Show the errors on the form:
$form.find('.payment-errors').text(response.error.message);
$form.find('.submit').prop('disabled', false); // Re-enable submission
} else { // Token was created!
// Get the token ID:
var token = response.id;
// Insert the token ID into the form so it gets submitted to the server:
$form.append($('<input type="hidden" name="stripeToken">').val(token));
// Submit the form:
$form.get(0).submit();
}
};
</script>
and in your controller:
public function subscription(Request $request)
{
$user = User::find(1);
$creditCardToken = $request->stripeToken;
$res = $user->newSubscription('main', 'pro')
->trialDays(30)
->create($creditCardToken, [
'plan' => 'pro',
'email' => $user->email,
]);
}

openshift form sendgrid ajax form html5 PHP BootStrap

I am trying to use an HTML form on openshift. The form controlled by Ajax. I can successfully send from OpenShift using a seperate page for the form, but I would like to use the BootStrap form. Bootstrap template is freelancer at Start BootStrap
I tried replacing the sendgrid code where the send php command was and moved return true to the end of the file.
working now-I must have had something wrong in my configuration. leaving here in case someone else wants to get a form working with openshift and sendgrid.
<?php
// Check for empty fields
if(empty($_POST['name']) ||
empty($_POST['email']) ||
empty($_POST['phone']) ||
empty($_POST['message']) ||
!filter_var($_POST['email'],FILTER_VALIDATE_EMAIL))
{
echo "No arguments Provided!";
return false;
}
// Create the email and send the message
$to = 'xxxx'; // Add your email address inbetween the '' replacing yourname#yourdomain.com - This is where the form will send a message to.
$email_subject = "Website Contact Form: $name";
$email_body = "You have received a new message from your website contact form.\n\n"."Here are the details:\n\nName: $name\n\nEmail: $email_address\n\nPhone: $phone\n\nMessage:\n$message";
$headers = "From: noreply#yourdomain.com\n"; // This is the email address the generated message will be from. We recommend using something like noreply#yourdomain.com.
$headers .= "Reply-To: $email_address";
//mail($to,$email_subject,$email_body,$headers);
// use actual sendgrid username and password in this section
$url = 'https://api.sendgrid.com/';
$user = 'xxxxx'; // place SG username here
$pass = 'xxxxx'; // place SG password here
// grabs HTML form's post data; if you customize the form.html parameters then you will need to reference their new new names here
$name = $_POST['name'];
$email = $_POST['email'];
$subject = $_POST['phone'];
$message = $_POST['message'];
// note the above parameters now referenced in the 'subject', 'html', and 'text' sections
// make the to email be your own address or where ever you would like the contact form info sent
$params = array(
'api_user' => "$user",
'api_key' => "$pass",
'to' => "xxxxx", // set TO address to have the contact form's email content sent to
'subject' => "Contact Form Submission", // Either give a subject for each submission, or set to $subject
'html' => "<html><head><title> Contact Form</title><body>
Name: $name\n<br>
Email: $email\n<br>
Subject: $subject\n<br>
Message: $message <body></title></head></html>", // Set HTML here. Will still need to make sure to reference post data names
'text' => "
Name: $name\n
Email: $email\n
Subject: $subject\n
$message",
'from' => "xxxxxx", // set from address here, it can really be anything
);
$request = $url.'api/mail.send.json';
// Generate curl request
$session = curl_init($request);
// Tell curl to use HTTP POST
curl_setopt ($session, CURLOPT_POST, true);
// Tell curl that this is the body of the POST
curl_setopt ($session, CURLOPT_POSTFIELDS, $params);
// Tell curl not to return headers, but do return the response
curl_setopt($session, CURLOPT_HEADER, false);
curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
// obtain response
$response = curl_exec($session);
curl_close($session);
return true;
?>
contact_me php from bootstrap theme
<?php
// Check for empty fields
if(empty($_POST['name']) ||
empty($_POST['email']) ||
empty($_POST['phone']) ||
empty($_POST['message']) ||
!filter_var($_POST['email'],FILTER_VALIDATE_EMAIL))
{
echo "No arguments Provided!";
return false;
}
$name = $_POST['name'];
$email_address = $_POST['email'];
$phone = $_POST['phone'];
$message = $_POST['message'];
// Create the email and send the message
$to = 'yourname#yourdomain.com'; // Add your email address inbetween the '' replacing yourname#yourdomain.com - This is where the form will send a message to.
$email_subject = "Website Contact Form: $name";
$email_body = "You have received a new message from your website contact form.\n\n"."Here are the details:\n\nName: $name\n\nEmail: $email_address\n\nPhone: $phone\n\nMessage:\n$message";
$headers = "From: noreply#yourdomain.com\n"; // This is the email address the generated message will be from. We recommend using something like noreply#yourdomain.com.
$headers .= "Reply-To: $email_address";
mail($to,$email_subject,$email_body,$headers);
return true;
?>
The working mailer.php
<?php
// use actual sendgrid username and password in this section
$url = 'https://api.sendgrid.com/';
$user = 'xxxxx'; // place SG username here
$pass = 'xxxxx'; // place SG password here
// grabs HTML form's post data; if you customize the form.html parameters then you will need to reference their new new names here
$name = $_POST['name'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$message = $_POST['message'];
// note the above parameters now referenced in the 'subject', 'html', and 'text' sections
// make the to email be your own address or where ever you would like the contact form info sent
$params = array(
'api_user' => "$user",
'api_key' => "$pass",
'to' => "xxxxx", // set TO address to have the contact form's email content sent to
'subject' => "Contact Form Submission", // Either give a subject for each submission, or set to $subject
'html' => "<html><head><title> Contact Form</title><body>
Name: $name\n<br>
Email: $email\n<br>
Subject: $subject\n<br>
Message: $message <body></title></head></html>", // Set HTML here. Will still need to make sure to reference post data names
'text' => "
Name: $name\n
Email: $email\n
Subject: $subject\n
$message",
'from' => "xxxxxxxx", // set from address here, it can really be anything
);
$request = $url.'api/mail.send.json';
// Generate curl request
$session = curl_init($request);
// Tell curl to use HTTP POST
curl_setopt ($session, CURLOPT_POST, true);
// Tell curl that this is the body of the POST
curl_setopt ($session, CURLOPT_POSTFIELDS, $params);
// Tell curl not to return headers, but do return the response
curl_setopt($session, CURLOPT_HEADER, false);
curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
// obtain response
$response = curl_exec($session);
curl_close($session);
// Redirect to thank you page upon successfull completion, will want to build one if you don't alreday have one available
header('Location: thanks.html'); // feel free to use whatever title you wish for thank you landing page, but will need to reference that file name in place of the present 'thanks.html'
exit();
// print everything out
print_r($response);
?>
the ajax file from the bootstrap template
$(function() {
$("input,textarea").jqBootstrapValidation({
preventSubmit: true,
submitError: function($form, event, errors) {
// additional error messages or events
},
submitSuccess: function($form, event) {
event.preventDefault(); // prevent default submit behaviour
// get values from FORM
var name = $("input#name").val();
var email = $("input#email").val();
var phone = $("input#phone").val();
var message = $("textarea#message").val();
var firstName = name; // For Success/Failure Message
// Check for white space in name for Success/Fail message
if (firstName.indexOf(' ') >= 0) {
firstName = name.split(' ').slice(0, -1).join(' ');
}
$.ajax({
url: "././mail/contact_me.php",
type: "POST",
data: {
name: name,
phone: phone,
email: email,
message: message
},
cache: false,
success: function() {
// Success message
$('#success').html("<div class='alert alert-success'>");
$('#success > .alert-success').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×")
.append("</button>");
$('#success > .alert-success')
.append("<strong>Your message has been sent. </strong>");
$('#success > .alert-success')
.append('</div>');
//clear all fields
$('#contactForm').trigger("reset");
},
error: function() {
// Fail message
$('#success').html("<div class='alert alert-danger'>");
$('#success > .alert-danger').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×")
.append("</button>");
$('#success > .alert-danger').append("<strong>Sorry " + firstName + ", it seems that my mail server is not responding. Please try again later!");
$('#success > .alert-danger').append('</div>');
//clear all fields
// $('#contactForm').trigger("reset");
},
})
},
filter: function() {
return $(this).is(":visible");
},
});
$("a[data-toggle=\"tab\"]").click(function(e) {
e.preventDefault();
$(this).tab("show");
});
});
/*When clicking on Full hide fail/success boxes */
$('#name').focus(function() {
$('#success').html('');
});
The bootstrap index.html form
<!-- Contact Section -->
<section id="contact">
<div class="container">
<div class="row">
<div class="col-lg-12 text-center">
<h2>Contact Me</h2>
<hr class="star-primary">
</div>
</div>
<div class="row">
<div class="col-lg-8 col-lg-offset-2">
<!-- To configure the contact form email address, go to mail/contact_me.php and update the email address in the PHP file on line 19. -->
<!-- The form should work on most web servers, but if the form is not working you may need to configure your web server differently. -->
<form name="sentMessage" id="contactForm" novalidate>
<div class="row control-group">
<div class="form-group col-xs-12 floating-label-form-group controls">
<label>Name</label>
<input type="text" class="form-control" placeholder="Name" id="name" required data-validation-required-message="Please enter your name.">
<p class="help-block text-danger"></p>
</div>
</div>
<div class="row control-group">
<div class="form-group col-xs-12 floating-label-form-group controls">
<label>Email Address</label>
<input type="email" class="form-control" placeholder="Email Address" id="email" required data-validation-required-message="Please enter your email address.">
<p class="help-block text-danger"></p>
</div>
</div>
<div class="row control-group">
<div class="form-group col-xs-12 floating-label-form-group controls">
<label>Phone Number</label>
<input type="tel" class="form-control" placeholder="Phone Number" id="phone" required data-validation-required-message="Please enter your phone number.">
<p class="help-block text-danger"></p>
</div>
</div>
<div class="row control-group">
<div class="form-group col-xs-12 floating-label-form-group controls">
<label>Message</label>
<textarea rows="5" class="form-control" placeholder="Message" id="message" required data-validation-required-message="Please enter a message."></textarea>
<p class="help-block text-danger"></p>
</div>
</div>
<br>
<div id="success"></div>
<div class="row">
<div class="form-group col-xs-12">
<button type="submit" class="btn btn-success btn-lg">Send</button>
</div>
</div>
</form>
</div>
</div>
</div>
</section>
Pardon me. The script works as is! I am not sure why it was not working, but I must have somehow corrupted my installation. I am leaving this up in case someone else wants to get emails working with openshift.

Resources