Wrong Securimage verification code still sends the form - php

First time poster, be gentle.
I have a form with a .php processing script that worked fine for the longest time except for the fact that I started to receive spam. I did some research on Captcha's and came across Securimage which was (supposedly) one of the easiest to implement. I downloaded the files and installed it into my script. I came across two problems.
The form was still sending if the captcha was left blank (it still notified me that it was blank).
The form was still sending if the captcha was wrong (it still notified me that it was wrong).
You can see it in action here: http://216.119.71.44/contact/
I "patched" issue 1 just by making the field a required field. I need some help fixing number 2. Below is my code and you can find the documentation for securimage here:
contact.php:
<?php
$thisPage = "Contact";
$errors = array();
$missing = array();
$date = date('F j, Y');
// check if the form has been submitted
if (isset($_POST['send'])) {
// sends the message to recipient
ini_set("SMTP","mail.abcprintingink.com");
// Please specify an SMTP Number 25 and 8889 are valid SMTP Ports.
ini_set("smtp_port","587");
// Please specify the return address to use
$to = 'paulr#abcprintingink.com'; //recipient's email address
$from = $_POST['email']; // this is the sender's Email address
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$subject = 'Online Form Submission';
$expected = array('fname','lname','email','phone','comments','captcha_code');
$required = array('fname','lname','email','phone','comments','captcha_code','');
$headers = "From: Technical Staffing Solutions";
// sends a copy of the message to the sender
$receiptHeader = "From: Technical Staffing Solutions";
$receiptSubject = "Copy of your form submission";
$receipt = "Hello " . $fname . "," . "\n" . "Below is a copy of the message you sent to us on " . $date . ". We will contact you as soon as possible. Thank you!" . "\n\n" . $_POST['comments'];
mail($from,$receiptSubject,$receipt,$receiptHeader);
// detailed processing script (checks for errors)
require('../include/processmail.php');
}
?>
<h1>CONTACT US</h1>
<?php
// Various on submit mail messages
if ($mailSent) {
echo "<div id=\"form-success\"><div>✓</div><p>Thank you " . $fname . ", your message has been sent.</p></div>";
}
elseif (($_POST && $suspect) || ($_POST && isset($errors['mailfail']))) {
echo "<div id=\"form-error\"><div>!</div><p>Your message could not be sent. Please try again.</p></div>";
}
elseif ($missing || $errors) {
echo "<div id=\"form-error\"><div>!</div><p>Please fill out the required fields and try again.</p></div>";
}
?>
<form id="getquote" method="post" action="" style="float:left;">
<input type="text" id="fname" name="fname" placeholder="First Name"
<?php if ($missing && in_array('fname', $missing)) { ?>style="border: 1px solid #cc0000;"
<?php } if ($missing || $errors) { echo 'value="' . htmlentities($fname, ENT_COMPAT, 'UTF-8') . '"'; } ?>>
<input type="text" id="lname" name="lname" placeholder="Last Name"
<?php if ($missing && in_array('lname', $missing)) { ?>style="border: 1px solid #cc0000;"
<?php } if ($missing || $errors) { echo 'value="' . htmlentities($lname, ENT_COMPAT, 'UTF-8') . '"'; } ?>>
<input type="email" id="email" name="email" placeholder="Email Address"
<?php if ($missing && in_array('email', $missing)) { ?>style="border: 1px solid #cc0000;"
<?php } if ($missing || $errors) { echo 'value="' . htmlentities($email, ENT_COMPAT, 'UTF-8') . '"'; } ?>>
<input type="text" id="phone" name="phone" placeholder="Phone Number"
<?php if ($missing && in_array('phone', $missing)) { ?>style="border: 1px solid #cc0000;"
<?php } if ($missing || $errors) { echo 'value="' . htmlentities($phone, ENT_COMPAT, 'UTF-8') . '"'; } ?>>
<textarea placeholder="How can I help you?" id="comments" name="comments"
<?php if ($missing && in_array('comments', $missing)) { ?>style="border: 1px solid #cc0000;"
<?php } if ($missing || $errors) { echo 'value="' . htmlentities($comments, ENT_COMPAT, 'UTF-8') . '"'; } ?>> </textarea><br>
<!-- Captcha -->
<img id="captcha" src="/securimage/securimage_show.php" alt="CAPTCHA Image" />
↻
<input type="text" id="captcha_code" name="captcha_code" size="10" maxlength="6"
<?php if ($missing && in_array('captcha_code', $missing)) { ?>style="border: 1px solid #cc0000;"
<?php } if ($missing || $errors) { echo 'value="' . htmlentities($captcha_code, ENT_COMPAT, 'UTF-8') . '"'; } ?>>
<!-- Submit -->
<div style="width:292px;"><input type="submit" id="send" name="send" value="SUBMIT"></div>
</form>
processmail.php:
<?php
session_start();
$suspect = false; //assume nothing is suspect
$pattern = '/Content-Type:|Bcc:|Cc:/i'; //create a pattern to locate suspect phrases
function isSuspect($val, $pattern, &$suspect) { //function to check for suspect phrases
if (is_array($val)) { //if the variable is an array, loop thorugh each element and pass it recursively back to the same function
foreach ($val as $item) {
isSuspect($item, $pattern, $suspect);
}
} else {
if(preg_match($pattern, $val)) {
$suspect = true;
}
}
}
if (!$suspect) {
foreach ($_POST as $key => $value) {
$temp = is_array($value) ? $value : trim($value); //assign to temporary variable and strip whitespace if not an array
if (empty($temp) && in_array($key, $required)) { //if empty and requires, add to $missing array
$missing[] = $key;
} elseif (in_array($key, $expected)) {
${$key} = $temp; //otherwise, assign to a variable of the same name as $key
}
}
}
if (!$suspect && !empty($email)) {
$validemail = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);
if ($validemail) {
$headers .= "\r\nReply-To: $validemail";
} else {
$errors['email'] = true;
}
}
$mailSent = false;
if (!$suspect && !$missing && !$errors) { //go ahead only if not suspect and all required fields are ok
$message = "";
foreach($expected as $item) { //loop through the $expected array
if (isset(${$item}) && !empty(${$item})) {
$val = ${$item};
} else {
$val = 'Not Selected'; //if it has no value, assign 'not selected'
}
if (is_array($val)) { //if an array, expand as comma-separated string
$val = implode(', ', $val);
}
$item = str_replace(array('_', '-'), ' ', $item); //replace underscores and hyphens in the label with spaces
$message .= ucfirst($item).": $val\r\n\r\n"; //add label and value to the message body
}
$message = wordwrap($message, 70); //limit the line length to 70 characters
$mailSent = mail($to, $subject, $message, $headers);
if (!$mailSent) {
$errors['mailfail'] = true;
}
}
include_once $_SERVER['DOCUMENT_ROOT'] . '/securimage/securimage.php';
$securimage = new Securimage();
if ($securimage->check($_POST['captcha_code']) == false) {
// the code was incorrect
// you should handle the error so that the form processor doesn't continue
// or you can use the following code if there is no validation or you do not know how
echo "The security code entered was incorrect.<br /><br />";
echo "Please go <a href='javascript:history.go(-1)'>back</a> and try again.";
exit;
}

Related

PHP form submits successfully, but does not redirect

I've gone through and read a bunch of other questions asked about this issue, but I'm still as confused now as when I started with this problem. From what I have read, I've learned the following:
I don't believe any html is being done before the header() - But I'm new at this still so I'm possibly wrong.
I haven't found any syntax errors.
The form submits ok and I receive test emails.
What happens is, I fill out the form completely with valid text and hit Submit. The data is submitted and sent to my email and the page refreshes back to a fresh contact form (contact.php) where it should be instead going to my thanks.php page.
Here is my code, email addresses changed.
Thank you in advance for any/all help! Much appreciated.
<?php
$errors = array();
$missing = array();
if (isset($_POST['send'])) {
$to = 'My Name <rawr#test.com>';
$subject = 'Feedback from Contact Form';
$expected = array('name', 'email', 'comments');
$required = array('name', 'email', 'comments');
$headers = "From: admin#website.com\r\n";
$headers .= "Content-Type: text/plain; charset=utf-8";
$authenticate = null;
if ($mailSent) {
header('Location: thanks.php');
exit();
}
}
include './navigation.php';
?>
<?php
//mail process **Don't Touch**
$suspect = false;
$pattern = '/Content-Type:|Bcc:|CC:/i';
function isSuspect ($val, $pattern, &$suspect) {
if (is_array($val)) {
foreach ($val as $item) {
isSuspect($item, $pattern, $suspect);
}
} else {
if (preg_match($pattern, $val)) {
$suspect = true;
}
}
}
isSuspect($_POST, $pattern, $suspect);
if (!$suspect) {
foreach ($_POST as $key => $value) {
$temp = is_array($value) ? $value : trim($value);
if (empty($temp) && in_array($key, $required)) {
$missing[] = $key;
$$key = '';
} elseif(in_array($key, $expected)) {
$$key = $temp;
}
}
}
if (!$suspect && !empty($email)) {
$validemail = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);
if ($validemail) {
$headers .= "\r\nReply-to: $validemail";
} else {
$errors['email'] = true;
}
}
if (!$suspect && !$missing && !$errors) {
$message = '';
foreach ($expected as $item) {
if (isset($$item) && !empty($$item)) {
$val = $$item;
} else {
$val = 'Not selected';
}
if (is_array($val)) {
$val = implode(', ', $val);
}
$item = str_replace(array('_', '-'), ' ', $item);
$message .= ucfirst($item) . ": $val\r\n\r\n";
}
$message = wordwrap($message, 70);
$mailSent = mail($to, $subject, $message, $headers, $authenticate);
if (!$mailSent) {
$errors['mailfail'] = true;
}
}
//end mail process
?>
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>Contact Carla <3</title>
<link href="/design.css" rel="stylesheet" type="text/css"/>
</head>
<body id="contact">
<div id="main">
<?php if (($_POST && $suspect) || ($_POST && isset($errors['mailfail']))) { ?>
<span class="warning">Sorry your mail could not be sent.</span>
<?php } elseif ($errors || $missing) { ?>
<span class="warning">Please fix the item(s) indicated.</span>
<?php } ?>
<form name="contact" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<p>
<label for="name">Name:
<?php if ($missing && in_array('name', $missing)) { ?>
<span class="warning">Who am I responding to?</span>
<?php } ?>
</label>
<br>
<input type="text" name="name" id="name"
<?php
if ($errors || $missing) {
echo 'value="' . htmlentities($name, ENT_COMPAT, 'utf-8') . '"';
}
?>
>
</p>
<p>
<label for="email">Email:
<?php if ($missing && in_array('email', $missing)) { ?>
<span class="warning">How will I respond to you?</span>
<?php } elseif (isset($errors['email'])) { ?>
<span class="warning">Invalid email address</span>
<?php } ?>
</label>
<br>
<input type="text" name="email" id="email"
<?php
if ($errors || $missing) {
echo 'value="' . htmlentities($email, ENT_COMPAT, 'utf-8') . '"';
}
?>
>
</p>
<p>
<label for="comments">Comments:
<?php if ($missing && in_array('comments', $missing)) { ?>
<span class="warning">Please say something..</span>
<?php } ?>
</label>
<br>
<textarea rows="7" cols="70" name="comments" id="comments"><?php
if ($errors || $missing) {
echo htmlentities($comments, ENT_COMPAT, 'utf-8');
}
?></textarea>
</p>
<p>
<input type="submit" name="send" id="send" value="Send Comments">
</p>
</form>
</div>
</body>
<?php include './footer.php'; ?>
</html>
Your problem is this line
if ($mailSent) {
header('Location: thanks.php');
exit();
}
You have not set $mailsent anywhere above that statement. So it is never getting to that point.
Once it has passed that part of your code it will not pop back up to check if mail sent unless you call a function or similar down lower that points to it.
I hope that sets you on the right path, let me know if you need further help.

How do I validate this email contact form with PHP?

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.
:)

do i need to add any code to PHP after using SSL

i'm using a simple contact form on my website using PHP, and i'm about to install SSL on my website, codewise do i need to make any changes to the PHP code, i'm totaly new to SSL and this is my first SSL installation .
<?php
$errors = array();
$missing = array();
if (isset($_POST['send'])) {
$to = 'john#example.com';
$subject = 'Feedback from contact form';
$expected = array('name', 'email', 'comments');
$required = array('name', 'email', 'comments');
$headers = "From: webmaster#example.com\r\n";
$headers .= "Content-type: text/plain; charset=utf-8";
require './includes/mail_process.php';
if ($mailSent) {
header('Location: thanks.php');
exit;
}
}
?>
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Contact Us</title>
<link href="./styles.css" rel="stylesheet" type="text/css">
</head>
<body>
<h1>Contact Us</h1>
<?php if ($_POST && $suspect) { ?>
<p class="warning">Sorry your mail could not be be sent.</p>
<?php } elseif ($errors || $missing) { ?>
<p class="warning">Please fix the item(s) indicated.</p>
<?php }?>
<form name="contact" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<p>
<label for="name">Name:
<?php if ($missing && in_array('name', $missing)) { ?>
<span class="warning">Please enter your name</span>
<?php } ?>
</label>
<input type="text" name="name" id="name"
<?php
if ($errors || $missing) {
echo 'value="' . htmlentities($name, ENT_COMPAT, 'utf-8') . '"';
}
?>
>
</p>
<p>
<label for="email">Email:
<?php if ($missing && in_array('email', $missing)) { ?>
<span class="warning">Please enter your email address</span>
<?php } elseif (isset($errors['email'])) { ?>
<span class="warning">Invalid email address</span>
<?php } ?>
</label>
<input type="text" name="email" id="email"
<?php
if ($errors || $missing) {
echo 'value="' . htmlentities($email, ENT_COMPAT, 'utf-8') . '"';
}
?>
>
</p>
<p>
<label for="comments">Comments:
<?php if ($missing && in_array('comments', $missing)) { ?>
<span class="warning">You forgot to add your comments</span>
<?php } ?>
</label>
<textarea name="comments" id="comments"><?php
if ($errors || $missing) {
echo htmlentities($comments, ENT_COMPAT, 'utf-8');
}
?></textarea>
</p>
<p>
<input type="submit" name="send" id="send" value="Send Comments">
</p>
</form>
<pre>
</body>
</html>
the mail_process.php goes like this
<?php
$suspect = false;
$pattern = '/Content-Type:|Bcc:|Cc:/i';
function isSuspect($val, $pattern, &$suspect) {
if (is_array($val)) {
foreach ($val as $item) {
isSuspect($item, $pattern, $suspect);
}
} else {
if (preg_match($pattern, $val)) {
$suspect = true;
}
}
}
isSuspect($_POST, $pattern, $suspect);
if (!$suspect) {
foreach ($_POST as $key => $value) {
$temp = is_array($value) ? $value : trim($value);
if (empty($temp) && in_array($key, $required)) {
$missing[] = $key;
$$key = '';
} elseif(in_array($key, $expected)) {
$$key = $temp;
}
}
}
if (!$suspect && !empty($email)) {
$validemail = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);
if ($validemail) {
$headers .= "\r\nReply-to: $validemail";
} else {
$errors['email'] = true;
}
}
if (!$suspect && !$missing && !$errors) {
$message = '';
foreach ($expected as $item) {
if (isset($$item) && !empty($$item)) {
$val = $$item;
} else {
$val = 'Not selected';
}
if (is_array($val)) {
$val = implode(', ', $val);
}
$item = str_replace(array('_', '-'), ' ', $item);
$message .= ucfirst($item) . ": $val\r\n\r\n";
}
$message = wordwrap($message, 70);
$mailSent = mail($to, $subject, $message, $headers, $authenticate);
if (!$mailSent) {
$errors['mailfail'] = true;
}
}
Since you don't have any absolute URL references you won't have a problem. I'd recommend you put this in your header (or at the top of all your PHP files) to force them to use https, that way if you did need absolute URLs in your website, you can have them all HTTPS as everyone would be forced there anyway.
if($_SERVER['HTTPS'] != 'on' || !stristr($_SERVER['HTTP_HOST'], 'www.')) {
$redirect= "https://www.".str_replace('www.','',$_SERVER['HTTP_HOST']).$_SERVER['REQUEST_URI'];
header("Location:$redirect");
}
You would have to change absolute URL's to "https://....". If you are not using absolute URL's there is nothing to change if your form and processing script are both on https.

AJAX with PHP self-submitting form and validation

I've been learning PHP via the book "PHP Solutions" by David Powers, which has a contact form with basic validation/error handling and input sanitization I would like to use without refreshing the page.
I'm testing this locally with XAMPP, and using the php form itself works perfectly: error messages display correctly, and if the form is successfully submitted, a thank you page is displayed and the form is delivered as an email to my test email address.
Now I need the form to submit and display error messages with AJAX. I've read many posts on accomplishing this, but I've been unsuccessful in implementing this. I've tried both the jQuery $.ajax and $.post methods - if the fields are all filled, the success message displays, but the message is not sent.
My guess is that javascript and php arrays are structured differently, but don't know how to reconcile this. I'm not even sure what the php processing scripts are getting/sending, if anything. How can I get this form to submit without refreshing the page, but still using the php scripts for server-side validation?
To simplify, I've stripped everything else from my page (and put all files in the same folder), except for the form: php, html, and the jQuery/AJAX I can't figure out.
Hope this makes sense. My 4 files:
mySite.js (the jQuery/AJAX I'm having trouble with...):
mySite = {
jsFormSubmission : function() {
$("#feedback").submit(function(event){
event.preventDefault();
var errorMsg = "<p class=\"errorBox\">Please fix the item(s) indicated.</p>";
var successMsg = "<p class=\"messageBox\">Thanks for the submission, your message has been sent.</p>";
var myObject = {
name : $("#name").val(),
email : $("#email").val(),
comments : $("#comments").val()
};
var ajaxData = JSON.stringify(myObject);
$.ajax({
type: 'POST',
url: 'form.php',
data: ajaxData,
success: function(data){
$(".formResult").html(successMsg);
},
error: function(http) {
$(".formResult").html(errorMsg);
alert(http.responseText);
}
});
});
}
};
The form (contact.php):
<?php include("form.php"); ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript" src=" mySite.js"></script>
<script type="text/javascript">
$(document).ready(function() {
mySite.jsFormSubmission();
});
</script>
</head>
<body>
<div id="contact">
<p class="formResult"></p>
<?php $errorForm = (($_POST && $suspect) || ($_POST && isset($errors['mailfail'])));
$errorTag = $missing || $errors;
if ($errorForm || $errorTag) { ?>
<p class="errorBox">
<?php } ?>
<?php if ($errorForm) { ?>
Sorry, your message could not be sent. Please try again later.
<?php } elseif ($errorTag) { ?>
Please fix the item(s) indicated.
<?php } ?>
<?php if ($errorForm || $errorTag) { ?>
</p>
<?php } ?>
<form id="feedback" method="post" action="">
<div class="tag">
<label id="lblName" for="name">Name:
<?php if ($missing && in_array('name', $missing)) { ?>
<span style="color:red; font-weight:bold;">Please enter your name</span>
<?php } ?>
</label>
<input name="name" id="name" type="text" class="formbox"
<?php if ($missing || $errors) {
echo 'value="' . htmlentities($name, ENT_COMPAT, 'UTF-8') . '"';
} ?>>
</div>
<div class="tag">
<label id="lblEmail" for="email">Email:
<?php if ($missing && in_array('email', $missing)) { ?>
<span style="color:red; font-weight:bold;">Please enter your email address</span>
<?php } elseif (isset($errors['email'])) { ?>
<span style="color:red; font-weight:bold;">Invalid email address</span>
<?php } ?>
</label>
<input name="email" id="email" type="text" class="formbox"
<?php if ($missing || $errors) {
echo 'value="' . htmlentities($email, ENT_COMPAT, 'UTF-8') . '"';
} ?>>
</div>
<div class="tag">
<label id="lblComments" for="comments">Comments:
<?php if ($missing && in_array('comments', $missing)) { ?>
<span style="color:red; font-weight:bold;">Please enter your message</span>
<?php } ?>
</label>
<textarea name="comments" id="comments" cols="60" rows="8"><?php
if ($missing || $errors) {
echo htmlentities($comments, ENT_COMPAT, 'UTF-8');
} ?></textarea>
</div>
<p>
<input name="send" id="send" type="submit" value="Send message">
</p>
</form>
</div>
</body>
</html>
form.php (included at top of contact.php):
<?php
$name = '';
$email = '';
$comments = '';
$required = '';
$errors = array();
$missing = array();
// check if the form has been submitted
if (isset($_POST['send'])) {
//email processing script
$to = 'johntest2#localhost';
$subject = 'Website contact form';
//list expected fields
$expected = array('name', 'email', 'comments');
// set required fields
$required = array('name', 'email', 'comments');
$headers = "From: Website Contact Test<johntest1#localhost>\r\n";
$headers .= 'Content-Type: text/plain; charset=utf-8';
require('processmail.php');
if ($mailSent) {
header("Location: thankYou.php#main");
$messageConfirm = true;
exit;
}
}
?>
processmail.php (validation scripts - included in form.php):
<?php
$suspect = false;
$pattern = '/Content-Type:|Bcc:|Cc:/i';
// function to check for suspect phrases
function isSuspect($val, $pattern, &$suspect) {
if (is_array($val)) {
foreach ($val as $item) {
isSuspect($item, $pattern, $suspect);
}
} else {
if (preg_match($pattern, $val)) {
$suspect = true;
}
}
}
isSuspect($_POST, $pattern, $suspect);
if (!$suspect) {
foreach ($_POST as $key => $value) {
$temp = is_array($value) ? $value : trim($value);
if (empty($temp) && in_array($key, $required)) {
$missing[] = $key;
} elseif (in_array($key, $expected)) {
${$key} = $temp;
}
}
}
// validate the user's email
if (!$suspect && !empty($email)) {
$validemail = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);
if ($validemail) {
$headers .= "\r\nReply-To: $validemail";
} else {
$errors['email'] = true;
}
}
$mailSent = false;
if (!$suspect && !$missing && !$errors) {
// initialize the $message variable
$message = '';
foreach($expected as $item) {
if (isset(${$item}) && !empty(${$item})) {
$val = ${$item};
} else {
$val = 'Not selected';
}
if (is_array($val)) {
$val = implode(', ', $val);
}
$item = str_replace(array('_', '-'), ' ', $item);
$message .= ucfirst($item).": $val\r\n\r\n";
}
$message = wordwrap($message, 70);
$mailSent = mail($to, $subject, $message, $headers);
if (!$mailSent) {
$errors['mailfail'] = true;
}
}
There's a few ways that you can get the error to display from the PHP side. You can throw an exception, which I wouldn't recommend, or use a header:
header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error', true, 500);
In your AJAX call, use the jQuery error callback:
$.ajax({
url: //url,
data: //data,
success: function (data) { //show success },
error: function () { //display code here }
});
You can also return the error in the body of the error message from the PHP side, and strip that from the body in your error callback.
PHP:
header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error', true, 500);
echo 'Your error message';
JavaScript:
error: function(http) {
// show http.responseText;
}
Also, for your form submission, pack your data into a object, and then serialize it. So:
var myObject = {
property1 : 'string',
property2 : [ 'array' ]
};
var ajaxData = JSON.stringify(myObject);

Ajax/PHP contact form not able to send mail

The funny thing is it did work for one evening. I contacted my host, and they are saying there's no reason it should not be working. I have also attempted to test it in Firebug, but it seemed to be sending. And I specifically put the email address (hosted in my domain) on my email safe list, so that is not the culprit either.
Would anyone here take a look at it for me? I'd be so grateful.
In the header I have:
<script type="text/javascript">
$(document).ready(function () {
var options = {
target: '#alert'
};
$('#contactForm').ajaxForm(options);
});
$.fn.clearForm = function () {
return this.each(function () {
var type = this.type,
tag = this.tagName.toLowerCase();
if (tag == 'form')
return $(':input', this).clearForm();
if (type == 'text' || type == 'password' || tag == 'textarea')
this.value = '';
else if (type == 'checkbox' || type == 'radio')
this.checked = false;
else if (tag == 'select')
this.selectedIndex = -1;
});
};
</script>
Here is the actual form:
<form id="contactForm" method="post" action="sendmail.php">
<fieldset>
<p>Email Me</p>
<div id="fieldset_container">
<label for="name">Your Name:</label>
<input type="text" name="name" id="name" /><br /><br />
<label for="email">Email:</label>
<input type="text" name="email" id="email" /><br /><br />
<span style="display:none;">
<label for="last">Honeypot:</label>
<input type="text" name="last" value="" id="last" />
</span><br /><br />
<label for="message">Comments & Inquiries:</label>
<textarea name="message" id="message" cols="" rows=""></textarea><br/>
</div>
<div id="submit_button">
<input type="submit" name="submit" id="submit" value="Send It" />
</div>
</fieldset>
</form>
<div class="message"><div id="alert"></div></div>
Here is the code from my validating page, sendmail.php:
<?php
// Who you want to recieve the emails from the form. (Hint: generally you.)
$sendto = 'my#emailaddress.com';
// The subject you'll see in your inbox
$subject = 'SH Contact Form';
// Message for the user when he/she doesn't fill in the form correctly.
$errormessage = 'There seems to have been a problem. May I suggest...';
// Message for the user when he/she fills in the form correctly.
$thanks = "Thanks for the email!";
// Message for the bot when it fills in in at all.
$honeypot = "You filled in the honeypot! If you're human, try again!";
// Various messages displayed when the fields are empty.
$emptyname = 'Entering your name?';
$emptyemail = 'Entering your email address?';
$emptymessage = 'Entering a message?';
// Various messages displayed when the fields are incorrectly formatted.
$alertname = 'Entering your name using only the standard alphabet?';
$alertemail = 'Entering your email in this format: <i>name#example.com</i>?';
$alertmessage = "Making sure you aren't using any parenthesis or other escaping characters in the message? Most URLS are fine though!";
//Setting used variables.
$alert = '';
$pass = 0;
// Sanitizing the data, kind of done via error messages first. Twice is better! ;-)
function clean_var($variable) {
$variable = strip_tags(stripslashes(trim(rtrim($variable))));
return $variable;
}
//The first if for honeypot.
if ( empty($_REQUEST['last']) ) {
// A bunch of if's for all the fields and the error messages.
if ( empty($_REQUEST['name']) ) {
$pass = 1;
$alert .= "<li>" . $emptyname . "</li>";
} elseif ( ereg( "[][{}()*+?.\\^$|]", $_REQUEST['name'] ) ) {
$pass = 1;
$alert .= "<li>" . $alertname . "</li>";
}
if ( empty($_REQUEST['email']) ) {
$pass = 1;
$alert .= "<li>" . $emptyemail . "</li>";
} elseif ( !eregi("^[_a-z0-9-]+(.[_a-z0-9-]+)*#[a-z0-9-]+(.[a-z0-9-]+)*(.[a-z]{2,3})$", $_REQUEST['email']) ) {
$pass = 1;
$alert .= "<li>" . $alertemail . "</li>";
}
if ( empty($_REQUEST['message']) ) {
$pass = 1;
$alert .= "<li>" . $emptymessage . "</li>";
} elseif ( ereg( "[][{}()*+?\\^$|]", $_REQUEST['message'] ) ) {
$pass = 1;
$alert .= "<li>" . $alertmessage . "</li>";
}
//If the user err'd, print the error messages.
if ( $pass==1 ) {
//This first line is for ajax/javascript, comment it or delete it if this isn't your cup o' tea.
echo "<script>$(\".message\").hide(\"slow\").show(\"slow\"); </script>";
echo "<b>" . $errormessage . "</b>";
echo "<ul>";
echo $alert;
echo "</ul>";
// If the user didn't err and there is in fact a message, time to email it.
} elseif (isset($_REQUEST['message'])) {
//Construct the message.
$message = "From: " . clean_var($_REQUEST['name']) . "\n";
$message .= "Email: " . clean_var($_REQUEST['email']) . "\n";
$message .= "Message: \n" . clean_var($_REQUEST['message']);
$header = 'From:'. clean_var($_REQUEST['email']);
//Mail the message - for production
mail($sendto, $subject, $message, $header, "-fstephanie#stephaniehenderson.com");
//This is for javascript,
echo "<script>$(\".message\").hide(\"slow\").show(\"slow\").animate({opacity: 1.0}, 4000).hide(\"slow\"); $(':input').clearForm() </script>";
echo $thanks;
die();
//Echo the email message - for development
echo "<br/><br/>" . $message;
}
//If honeypot is filled, trigger the message that bot likely won't see.
} else {
echo "<script>$(\".message\").hide(\"slow\").show(\"slow\"); </script>";
echo $honeypot;
}
?>
If the message is echoing then it's not a problem with your javascript or html. I would suggest making a fresh PHP file with only the 1 line that attempts to send mail:
mail('youremailaddress#example.com', 'My Subject', 'This is a message');
Hardcode everything. If that works, then you know that it's probably not a problem with your host, and you need to examine that line and the variables to are passing to mail()

Categories