PHP to post to different user dependent on form name - php

Trying to work out the best way to get the PHP below to post to a different user email address dependent on the form name it is coming from.
Eg. this form is name="engineering-australia" and I have others with different names. I want this one to go to user1#domain.com and an other to go to user2#domain.com and so on.
My question is, what would be the best way to do this, I don't want to use javascript- I was thinking some kind of if statement? But wouldn't the form name need to be pulled in somehow?
Also worth mentioning the forms are identical apart from the form name, I didn't want to just create a different PHP script for each form.
HTML
<form class="form-contact" name="engineering-australia">
<fieldset>
<input id="form-name" name="name" type="text" placeholder="Your Name" />
<input id="form-email" name="email" type="text" placeholder="Your Email" />
</fieldset>
<textarea id="form-msg" name="message" rows="10" placeholder="Your Message" ></textarea>
<input type="submit" name="submit" class="button button-small" value="Send Message" />
</form>
PHP
<?php
define('kOptional', true);
define('kMandatory', false);
error_reporting(E_ERROR | E_WARNING | E_PARSE);
ini_set('track_errors', true);
function DoStripSlashes($fieldValue) {
// temporary fix for PHP6 compatibility - magic quotes deprecated in PHP6
if ( function_exists( 'get_magic_quotes_gpc' ) && get_magic_quotes_gpc() ) {
if (is_array($fieldValue) ) {
return array_map('DoStripSlashes', $fieldValue);
} else {
return trim(stripslashes($fieldValue));
}
} else {
return $fieldValue;
}
}
function FilterCChars($theString) {
return preg_replace('/[\x00-\x1F]/', '', $theString);
}
function CheckEmail($email, $optional) {
if ( (strlen($email) == 0) && ($optional === kOptional) ) {
return true;
} elseif ( preg_match("/^([\w\!\#$\%\&\'\*\+\-\/\=\?\^\`{\|\}\~]+\.)*[\w\!\#$\%\&\'\*\+\-\/\=\?\^\`{\|\}\~]+#((((([a-z0-9]{1}[a-z0-9\-]{0,62}[a-z0-9]{1})|[a-z])\.)+[a-z]{2,6})|(\d{1,3}\.){3}\d{1,3}(\:\d{1,5})?)$/i", $email) == 1 ) {
return true;
} else {
return false;
}
}
if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$clientIP = $_SERVER['HTTP_X_FORWARDED_FOR'];
} else {
$clientIP = $_SERVER['REMOTE_ADDR'];
}
$FTGname = DoStripSlashes( $_POST['name'] );
$FTGemail = DoStripSlashes( $_POST['email'] );
$FTGmessage = DoStripSlashes( $_POST['message'] );
$FTGsubmit = DoStripSlashes( $_POST['submit'] );
$validationFailed = false;
# Fields Validations
if (!CheckEmail($FTGemail, kMandatory)) {
$FTGErrorMessage['email'] = 'ERROR MESSAGE';
$validationFailed = true;
}
# Redirect user to error message
if ($validationFailed === true) {
header("Location: index.php?success=2");
}
if ( $validationFailed === false ) {
# Email to Form Owner
$emailSubject = FilterCChars("Website Enquiry");
$emailBody = chunk_split( base64_encode( "<html>\n"
. "<head>\n"
. "<title></title>\n"
. "</head>\n"
. "<body>\n"
. "Name : $FTGname<br />\n"
. "Email : $FTGemail<br />\n"
. "Message : " . nl2br( $FTGmessage ) . "\n"
. "</body>\n"
. "</html>" ) )
. "\n";
$emailTo = 'User <user1#domain.com>';
$emailFrom = FilterCChars("$FTGemail");
$emailHeader = "From: $emailFrom\n"
. "MIME-Version: 1.0\n"
. "Content-Type: text/html; charset=\"UTF-8\"\n"
. "Content-Transfer-Encoding: base64\n"
. "\n";
mail($emailTo, $emailSubject, $emailBody, $emailHeader);
# Redirect user to success message
header("Location: index.php?success=1");
}
?>

You're not going to get the form name in PHP. Try using a hidden input in each form:
<input name="form" type="hidden" value="engineering-australia" />
Then check $_POST['form'] in PHP.
switch($_POST['form']) {
case 'engineering-australia':
$email = 'user1#domain.com';
break;
case 'something-else':
$email = 'user2#domain.com';
break;
}

Change:
<form class="form-contact" name="engineering-australia">
<fieldset>
To:
<form class="form-contact">
<input type="hidden" name="post-to" value="engineering-australia" />
<fieldset>
Now you can check who you want to send the email to by simply requesting $_POST['post-to'] on the submit action page.

Related

Wrong Securimage verification code still sends the form

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

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

error on contact form submit via jquery ajax

Based on this question i had to rewrite my contact form script.
The goal is to to have a send button labeled send. After clickick it should show sending till the php script is done. When its done it should show sent.
Thats my simple form:
<form id="contactForm" action="mail.php" method="post">
<input type="text" id="name" name="name" placeholder="Name" required><br />
<input type="text" id="email" name="email" placeholder="Mail" required><br />
<textarea name="message" id="message" placeholder="Nachricht" required></textarea><br />
<button name="submit" type="submit" id="submit">send</button>
</form>
Here is the jquery script for the label changing and the ajax submit.
<script>
$( init );
function init() {
$('#contactForm').submit( submitForm );
}
function submitForm() {
var contactForm = $(this);
if ( !$('#name').val() || !$('#email').val() || !$('#message').val() ) {
$('#submit').html('error');
} else {
$('#submit').html('sending');
$.ajax( {
url: contactForm.attr( 'action' ) + "?ajax=true",
type: contactForm.attr( 'method' ),
data: contactForm.serialize(),
success: submitFinished
} );
}
return false;
}
function submitFinished( response ) {
response = $.trim( response );
if ( response == "success" ) {
$('#submit').HTML = ('sent');
} else {
$('#submit').html('error');
}
}
</script>
the mail.php:
<?php
define( "RECIPIENT_NAME", "John Doe" );
define( "RECIPIENT_EMAIL", "john#doe.com" );
define( "EMAIL_SUBJECT", "Subject" );
$success = false;
$name = isset( $_POST['name'] ) ? preg_replace( "/[^\.\-\' a-zA-Z0-9]/", "", $_POST['name'] ) : "";
$email = isset( $_POST['email'] ) ? preg_replace( "/[^\.\-\_\#a-zA-Z0-9]/", "", $_POST['email'] ) : "";
$message = isset( $_POST['message'] ) ? preg_replace( "/(From:|To:|BCC:|CC:|Subject:|Content-Type:)/", "", $_POST['message'] ) : "";
if ( $name && $email && $message ) {
$recipient = RECIPIENT_NAME . " <" . RECIPIENT_EMAIL . ">";
$headers = "Von: " . $name . " <" . $email . ">";
$success = mail( $recipient, EMAIL_SUBJECT, $message, $headers );
}
if ( isset($_GET["ajax"]) ) {
echo $success ? "success" : "error";
} else {
//add html for javascript off user
}
?>
Its submits correct and i get the mail but i doesnt change the label to sent.Its stuck at sending.
Any idea or suggestions whats wrong with my code?
best regards
dennym
The error is on this line:
$('#submit').HTML = ('sent');
Change that to:
$('#submit').html('sent');
$('#submit').HTML = ('sent');
should be
$('#submit').html('sent');
like you have everywhere else.
You have to change
$('#submit').HTML = ('sent');
to:
$('#submit').html('sent');
in your function submitFinished();

noob: display err_msg on page (pt. 2)

I posted this yesterday, so I apologize if you responded and are frustrated at seeing this again! But the form isn't working at all now, and I'd appreciate some help in solving this problem.
I have a form that sends data to a database, and requires validation. Yesterday it was at least validating correctly, but today I can't even get it to hook to my action page correctly. Here are the two pages:
Page w/ form:
<?php
session_start();
$form_field = array(
'First_Name' => '',
'Last_Name' => '',
'Business_Name' => '',
'Phone_Number' => '',
'Web_Address' => '',
'Email_Address' => '',
'How_selling_product' => '',
'Where_did_you_hear_about_us' => '',
);
foreach($form_field as $key => $value){$profiledata[$key]='';}
if(!empty($_SESSION['profiledata'])){
$profiledata = $_SESSION['profiledata'];
}
?>
[js]
function MM_findObj(n, d) { //v4.01
var p,i,x; if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
if(!x && d.getElementById) x=d.getElementById(n); return x;
}
function MM_validateForm() { //v4.0
var i,p,q,nm,test,num,min,max,errors='',args=MM_validateForm.arguments;
errors += addValidation("req","first_name","- First Name is required.");
errors += addValidation("req","last_name","- Last Name is required.");
for (i=0; i<(args.length-2); i+=3) { test=args[i+2]; val=MM_findObj(args[i]);
if (val) { nm=val.name; if ((val=val.value)!="") {
if (test.indexOf('isEmail')!=-1) { p=val.indexOf('#');
if (p<1 || p==(val.length-1)) errors+='- '+nm+' must contain an e-mail address.\n';
} else if (test!='R') { num = parseFloat(val);
if (isNaN(val)) errors+='- '+nm+' must contain a number.\n';
if (test.indexOf('inRange') != -1) { p=test.indexOf(':');
min=test.substring(8,p); max=test.substring(p+1);
if (num<min || max<num) errors+='- '+nm+' must contain a number between '+min+' and '+max+'.\n';
} } } else if (test.charAt(0) == 'R') errors += '- '+nm+' is required.\n'; }
}
errors += addValidation("req","security_code","- Security Code is required.");
if(!errors){
errors += addValidation("valid_lastname","first_name","- Please enter valid First Name");
errors += addValidation("valid_lastname","last_name","- Please enter valid Last Name");
errors += addValidation("numhyphenbrace","phone number","- Please enter valid Phone Number");
errors += addValidation("valid_url","web address","- Please Enter Valid Web Address");
errors += addValidation("email","email address","- Please Enter Valid Email");
}
if (errors) alert('The following error(s) occurred:\n'+errors);
document.MM_returnValue = (errors == '');
}
[/js]
<h1>Some content</h1>
<p>Some text</p>
<form id="form1" name="form1" method="post" action="mailform" onsubmit="MM_validateForm('Name','','R','Business Name','','R','Email Address','','R','How selling product','','R','Where did you hear about us','','R');return document.MM_returnValue">
<div style="color:#FF0000; text-align:center;"><?php if(!empty($_GET['err_msg'])){echo $_GET['err_msg'];} ?></div>
<fieldset>
<legend>Contact form</legend>
<p class="first">
<label for="name">First Name</label>
<input type="text" name="First Name" id="first_name" size="30" value="<?=htmlentities($profiledata['First_Name'])?>" />
</p>
<p class="first">
<label for="name">Last Name</label>
<input type="text" name="Last Name" id="last_name" size="30" value="<?=htmlentities($profiledata['Last_Name'])?>" />
</p>
<p>
<label for="name">Phone Number</label>
<input type="text" name="Phone Number" id="phone number" size="30" value="<?=$profiledata['Phone_Number']?>" />
</p>
<p>
<label for="email">Business Name</label>
<input type="text" name="Business Name" id="business name" size="30" value="<?=htmlentities($profiledata['Business_Name'])?>" />
</p>
<p>
<label for="email">Web Address</label>
<input type="text" name="Web Address" id="web address" size="30" value="<?=$profiledata['Web_Address']?>" />
</p>
<p>
<label for="email">Email</label>
<input type="text" name="Email Address" id="email address" size="30" value="<?=$profiledata['Email_Address']?>" />
</p>
</fieldset>
<fieldset>
<p>
<label for="message">Describe how you plan on selling this product</label>
<textarea name="How selling product" id="How selling product" cols="30" rows="4"><?=htmlentities($profiledata['How_selling_product'])?></textarea>
</p>
<p>
<label for="message">Where did you hear about us?</label>
<textarea name="Where did you hear about us" id="Where did you hear about us" cols="30" rows="4"><?=htmlentities($profiledata['Where_did_you_hear_about_us'])?></textarea>
</p>
<p>
<img src="CaptchaSecurityImages.php?width=100&height=40&characters=5" /><br />
<label for="security_code">Security Code: </label><input id="security_code" name="security_code" type="text" />
</p>
</fieldset>
<p class="submit"><button type="submit">Send</button></p>
<input name="mailform_address" type="hidden" value="email#address.com" />
</form>
Mailform.php success:
<?php
session_start();
include("connect.php");
function valid_email($str)
{
return ( ! preg_match("/^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*#([a-z0-9\-]+\.)+[a-z]{2,6}$/ix", $str)) ? FALSE : TRUE;
}
function is_url($str)
{
return ( ! preg_match("/^((www)\.)?((\w+|[\d]?+)+(\.|\-)(\w+[\d]?+))+(\w)$/", $str)) ? FALSE : TRUE;
}
function valid_phone($str)
{
$Num = $str;
$Num = ereg_replace("([ ]+)","",$Num);;
$Num = eregi_replace("(\(|\)|\-|\+)","",$Num);
if(!is_numeric($Num))
{
return FALSE;
}
else
return TRUE;
}
$form_field = array(
'First_Name' => '',
'Last_Name' => '',
'Business_Name' => '',
'Phone_Number' => '',
'Web_Address' => '',
'Email_Address' => '',
'How_selling_product' => '',
'Where_did_you_hear_about_us' => '',
);
foreach($form_field as $key => $value){$profiledata[$key]=trim($_POST[$key]);}
$_SESSION['profiledata'] = $profiledata;
$emailto = NULL;
$emailmessage = "Dealer Contact Form\n";
$emailsubject = "Dealer Contact Form";
if(!empty($_POST)){
//echo "<pre>";print_r($_POST);die;
if( $_SESSION['security_code'] != $_POST['security_code'] || empty($_SESSION['security_code'] ) ) {
// Insert your code for showing an error message here
$err_msg = 'Sorry, you have provided an invalid security code';
header("Location: reseller.php?err_msg=".urlencode($err_msg));
return;
} else {
unset($_SESSION['security_code']);
}
$fname = html_entity_decode(trim($_POST['First_Name']));
$lname = html_entity_decode(trim($_POST['Last_Name']));
$company = html_entity_decode(trim($_POST['Business_Name']));
$phone = html_entity_decode(trim($_POST['Phone_Number']));
$website = html_entity_decode(trim($_POST['Web_Address']));
$email = html_entity_decode(trim($_POST['Email_Address']));
$notes = "Lead Source: ".html_entity_decode(trim($_POST['Where_did_you_hear_about_us']))."\n";
$notes .= "Selling Method: ".html_entity_decode(trim($_POST['How_selling_product']));
if(!valid_phone($phone)){
$err_msg = 'Please enter valid Phone Number.';
header("Location: reseller.php?err_msg=".urlencode($err_msg));
return;
}
if(!is_url($website)){
$err_msg = 'Please enter valid Web Address.';
header("Location: reseller.php?err_msg=".urlencode($err_msg));
return;
}
if(!valid_email($email)){
$err_msg = 'Please enter valid Email.';
header("Location: reseller.php?err_msg=".urlencode($err_msg));
return;
}
if(!stristr($website,"http://") && !stristr($website,"https://") && $website){
$website = "http://".$website;
}
$res = mysql_query("SELECT in_customer_id FROM tbl_customer WHERE st_company_name = '".addslashes($company)."'");
if(mysql_num_rows($res)){
$err_msg = 'Business Name already exists';
header("Location: reseller.php?err_msg=".urlencode($err_msg));
return;
}
$res = mysql_query("SELECT st_user_name,st_user_email_id FROM tbl_admin_user WHERE st_user_email_id='".addslashes($email)."' AND flg_is_delete=0");
if(mysql_num_rows($res)){
$err_msg = 'Email already exists';
header("Location: reseller.php?err_msg=".urlencode($err_msg));
return;
}
$sql_customer = "INSERT INTO tbl_customer (`st_company_name`, `in_customer_type`, `st_customer_account`, `in_customer_phone_number`, `flg_customer_account_type`, `flg_disable_ordering`, `st_message`, `in_status`, `dt_added_date`, `st_web`, `st_notes`) VALUES ('".addslashes($company)."', '2', '".time()."', '".addslashes($phone)."', '0', '1', 'You are an Inquiry customer', '0', '".date("Y-m-d H:i:s")."', '".addslashes($website)."', '".addslashes($notes)."')";
mysql_query($sql_customer);
$cust_id = mysql_insert_id();
if($cust_id){
$sql_user = "INSERT INTO tbl_admin_user (`st_user_first_name`, `st_user_last_name`, `st_user_company_name`, `st_user_email_id`, `in_customer_id`) VALUES ('".addslashes($fname)."', '".addslashes($lname)."', '".addslashes($company)."', '".addslashes($email)."', '".$cust_id."')";
mysql_query($sql_user);
$msg = "";
$sub = "Thank you for contacting us.";
ob_start();
include("mailformat.php");
$msg = ob_get_contents();
ob_end_clean();
$headers = '';
//$headers = "MIME-Version: 1.0\r\n";
$headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";
$headers .= "From: " . $_POST['mailform_address'] . "\r\n";
$headers .= "Reply-To: ". $_POST['mailform_address'] . "\r\n";
$headers .= "Bcc: email#address.com";
if (#mail($email, $sub, $msg, $headers))
{
session_unset('profiledata');
}
}
foreach($_POST as $name => $value)
{
if ($name == 'mailform_address')
{
$emailto = $value;
}
elseif($name != "security_code")
{
$emailmessage .= $name . ": " . $value . "\n";
}
}
session_unset('profiledata');
}
?>
<?
if (#mail($emailto, $emailsubject, $emailmessage))
{
?>
<p>We'll be in touch within two business days. If you haven't heard back from us within two business days, please contact us</p>
<?
}
else
{
?>
<p>E-mail could not be sent. Please contact us.</p>
<?
}
?>
Thanks for helping me out.
I admit that I haven't read your code thoroughly, but any of these might be your problem:
In the call to MM_validateForm() in your script, I think you need to pass the names of your HTML form fields but though every argument seems correct, the first one is 'Name' that doesn't seem to be a valid form field.
What is the function addValidation() in MM_validateForm() and what does it do? Since I do not see its definition, I assume it might be generating errors in your JS.
In MM_validateForm(), after line no. 3 & 4, it seems that the variable errors is never empty and thus preventing your form to submit?
I'm not very clear at which point are you stuck - is your form not submitting at all? Did you try to do an alert of errors variable at the end of MM_validateForm(). Perhaps it might help.

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