Page 1 of 1

Form submits only some info through email

Posted: Mon Jun 27, 2011 7:53 pm
by mynahbird
Aloha ~ I am having problems with my code not submitting all variables. The following is excepts from an html form which also includes name address, etc. The Brochure_Number and most all the other variables appear on the emailed form, but ..

1) Date_Purchased, what code needed to get the date printed on the brochure to appear in the email? I get it with php current date code; but am confused as to what code to receive inputed data: Month, Day, Year. Don't really want to do a pop up calendar because of conflicting codes within the page, like JSs Is their a shorter way?

2) Where ~ Does not go through to the emailed form. I don't know why. Can't find the error, Please Help

Code: Select all

<form method="post" action="contactengine.php">

<input type="text" name="Brochure_Number" value="" id="Brochure_Number" />
<label for="Where">Where or who did you purchase your Brochure from?:</label>

<label for="Date_Purchased">Date_Purchased:</label>
<input type="text" name="Date_Purchased" value="" id="Date_Purchased" />


<label for="Where">Where or who did you purchase your Brochure from?:</label>
<input type="text" name="Where" value="" id="Where" size="50" />

<input type="submit" name="submit" value="Submit" class="submit-button" />

</form>

The following is the complete php code on ...... contactengine.php ~

Code: Select all

<?php

$EmailFrom = "register@sunnycarpet.com";
$EmailTo = "info@sunnycarpet.com";

$Brochure_Number=($_POST['Brochure_Number']);
$Date_Purchased=($_POST['Date_Purchased']);
$Name=($_POST['Name']); 
$Street=($_POST['Street']); 
$City=($_POST['City']); 
$Zip=($_POST['Zip']); 
$Phone=($_POST['Phone']);
$Cell=($_POST['Cell']);
$Email=($_POST['Email']);
$Sq_Ft=($_POST['Sq_Ft]);


$to=$EmailTo;
$subject="Brochure Registration";

$message="Brochure_Number: $Brochure_Number\nDate_Purchased: $Date_Purchased\nFrom: $Name\nStreet: $Street\nCity: $City\nZip: $Zip\nPhone: $Phone\nCell: $Cell\nEmail: $Email\nSq_Ft: $Sq_Ft\nOwn: $Own\nRent: $Rent\nWhere: $Where\n".$message;

@mail($to,$subject,$message,$headers);

// redirect to success page 

if (@mail){
  print "<meta http-equiv=\"refresh\"
content=\"0;URL=http://sunnycarpet.com/thanks.html\">";
}
else{
  print "<meta http-equiv=\"refresh\"
content=\";0;URL=error.htm\">";
}
?>
All help is welcome, my brain is crying out for help! Mahalo for your kokua! ~S~ :crazy: :crazy:

Re: Form submits only some info through email

Posted: Mon Jun 27, 2011 11:13 pm
by twinedev
Here is an example script you can use and modify for sending things like contact forms.

Some extra features (some are explained more below):
  1. The form and processing are on the same file, this way, if part of the input fails validation, the form is redisplayed WITH the data they already entered
  2. Processing of the fields is for the most part automatic, just add them into the form (and optional validation) and they are good to go. System automatically coverts named fields like txtFirstName or txtFirst_Name to show up as First Name:
  3. If you need to change TO/FROM information, easily found at the top as a constant
  4. bot/spam prevention features - honeypot and time check
  5. Code is set up to allow validation of inputs, see the current ones as examples for how to do your own
  6. Includes the URL to the form as well as senders IP
  7. For <textarea> inputs, cleanly wraps the content so when an "newline" is encountered, each addtional line is indented the same amount as label for easier reading/printing (if displayed using fixed width font)
Here is a sample of the mailing from the form as set up in the code below:
[text]The following form was submitted 23:39:07 on 06/27/2011
=======================================================
First Name: Test
Last Name: User
DOB: 9/14/39
State: Ohio
Comments: This is a comment, line #1
This is line 2 of that comment

And here is line 4 (3 was blank)

=======================================================
Form URL: http://www.example.com/emailform.php
Submitted from IP 192.168.0.72[/text]
Notes on the code:

Honeypot/time check to prevent spam bots
This helps prevent automated submission of your form (usually to spam websites). There are two methods.

The first is a Honeypot. This is a field that for the majority of users is hidden from view, named something catchy a bot would look for (URL in this case, they love to post URLs ya know). The idea is that for the form to properly submit, this field must be left blank. Bots even if they are not looking at the field names will usually submit something to EVERY field.

The second method is time stamping the form. This comes from code I normally put on Word Press sites, as there are bots out there that look for them and know by default what URL/fields to post to the server to submit things like comments. I just carry it over to most of my forms now. Basically, there is a hidden field on the form that represents the timestamp the form was loaded by the user. (it is converted to HEX value and then reversed to make it less obvious this is what it is). The idea here is if a bot does come to your site, records what fields to submit, well after a set period of time (60 minutes coded below) their submissions will be no good as they will be submitting the original timestamp.

Little things help cut back on the crap without actually using something as ugly as Captcha

Field types
Most fields just need to start with txt, such as txtFieldName. When the form submits, as mentioned it will convert (gets rid of txt, and then any uppercase letter following a number, a lowercase letter and/or _ will get coverted to have a space between them (underscores removed).

Coming from the standpoint of database handled forms, drops downs such as states I handle as an numeric indexed array (again from DB). Their field names start with drp You can use whatever key/value method you want, the actual value is what is e-mailed. if you do numeric, you do not have to program a number for them all, you can do like the following, but be sure the first one is set to 1 (0 = "Select One" in the drop down)

Code: Select all

$aryList['Mood'] = array(1=>'Happy','Sad','Silly','Bored');
(these are set up around lines 10-12) Also, there is a block of code for setting the "default" value for a new form (around line 100). While text inputs do not have to be defined, make sure you set a default for all drpWhatevers (even if it is 0 for "Select One")

This form does not go into checkboxes and multiple selects, it is just basic.

Anyhow, here is the sample code, if you have any questions, let me know.

-Greg

Code: Select all

<?php

define ('MINUTES_TO_SUBMIT',60); // HOW MANY MINUTES THEY HAVE TO SUBMIT THE FORM (prevent Curl calls)
define ('MAIL_TO', 'info@sunnycarpet.com');
define ('MAIL_FROM', 'register@sunnycarpet.com');
define ('MAIL_SUBJECT','Brochure Registration');

$aryErr = array(); // Will hold error messages

// Note, need to load up an array of states here... either from Database or an include...
$aryList = array();
$aryList['State'] = array(35=>'Ohio',36=>'Oklahoma',37=>'Oregon',38=>'Pennsylvania');


// Note, I use a honeypot to help prevent bot spam see end of <form> code
if (count($_POST)>0 && isset($_POST['hidPostHash']) && isset($_POST['URL']) && $_POST['URL']=='') { // Form submitted

	// Clear any fiels with just whitespace back to being blank for validation
	foreach($_POST as $key=>$val) { if (is_string($val)) ($_POST[$key]=trim($val)); }

	// BEGIN: Validation

		// Required fields

		if (!isset($_POST['txtFirstName']) || strlen($_POST['txtFirstName'])<3) {
			$aryErr['FirstName'] = 'First Name must be at least 3 characters';
		}
		if (!isset($_POST['txtLastName']) || strlen($_POST['txtLastName'])<3) {
			$aryErr['LastName'] = 'First Name must be at least 3 characters';
		}
		if (!isset($_POST['drpState']) || (int)$_POST['drpState']==0) {
			$aryErr['State'] = 'You must select a state';
		}

		// Optional Fields that require certain formats (dates/phone numbers)

		if (isset($_POST['txtDOB']) && $_POST['txtDOB']!='') {
			if (!preg_match('%^\d?\d[-/]\d?\d[-/]\d\d(\d\d)?$%',$_POST['txtDOB'])) {
				$aryErr['DOB'] = 'Date of birth must be left blank or be in MM-DD-YYYY format';
			}
			else {
				// Note, other checking should be done to make sure a valid date at least 13 years ago
			}
		}

		// Make sure they submitted it in a timely fashion, (ie not a programmed bot) if no other errors

		if (count($aryErr) == 0) {
			$tsOriginalForm = (int)hexdec(strrev($_POST['hidPostHash']));

			if ($tsOriginalForm + (MINUTES_TO_SUBMIT*60) < time()) {
				$aryErr['FORM'] = "You took too long submitting this form, try again";
			}
		}

	// END: Validation

	if (count($aryErr)==0) { // All submited data is good

		// This block is based upon that all fields that should go to DB are prefixed with either:
		//    txt = text data
		//    drp = numeric data from a dropdown/option list which will be a key to an array of items (loaded in @ line 8)
		//    If you have others, just keep adding elseif's to handle those

		$aryMsg = array(); // Only add  \n to the end of lines where you need a blank line
		$aryMsg[] = 'The following form was submitted '.date('H:i:s \o\n m/d/Y');
		$aryMsg[] = '=======================================================';
		foreach ($_POST as $key=>$val) {
			$strPrefix = substr($key,0,3); // used more than once, store it
			if (strlen($key)>4) {
				$strField = substr($key,3);
				$strLabel = preg_replace('/([a-z0-9])_?([A-Z])/', '\1 \2',$strField).': ';
				if ($strPrefix=='txt') {
					$aryMsg[] = $strLabel.str_replace("\n","\n".str_repeat(' ',strlen($strLabel)),$val);
				}
				elseif ($strPrefix=='drp' && isset($aryList[$strField])) {
					$aryMsg[] = $strLabel.$aryList[$strField][$val];
				}
			}
		}

		// Footer of the message to identify where the form was submitted from and the users IP address
		$aryMsg[] = "\n=======================================================";
		$aryMsg[] = 'Form URL: '.(($_SERVER['SERVER_PORT']==80)?'http://':'https://').$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
		$aryMsg[] = 'Submitted from IP '.$_SERVER['REMOTE_ADDR'];

		if (mail(MAIL_TO,MAIL_SUBJECT,implode("\n",$aryMsg),'From: '.MAIL_FROM)) {
			header('Location: http://sunnycarpet.com/thanks.html');
		}
		else {
			header('Location: http://'.$_SERVER['HTTP_HOST'].'/error.htm');
		}
		exit;
	} // END: if (count($aryErr)==0)
}
else {
	// The form was not submitted, for ALL drpWhatever fields, define their defaults.
	// The function below handles txt fields, so no need to prefine them unless you want them filled

	$_POST['drpState'] = 35; // For me, auto selects Ohio
}

$strPostHosh = strrev(dechex(time()));

function echo_value($key) {
	if (isset($_POST['txt'.$key])) {
		echo htmlspecialchars($_POST['txt'.$key]);
	}
}

?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
	<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
	<title>My Site - Give me some data!</title>
</head>
<body>
	<h1>Submit me some data!</h1>
	<p>Please use the following form to sign up/suggest something/contact us... whatever...</p>
	<div id='form-error'>
		<?php if (count($aryErr)>0): ?>
			<p>The following errors were found:</p>
			<?php echo '<ul><li>',implode('</li><li>',$aryErr),'</li></ul>'; ?>
		<?php endif; ?>
	</div>
	<form method="post" action="#">
		<p>All fields marked with a * are required.</p>

		<ul style="list-style-type: none; padding: 0; margin-left: 0;">
			<li>
				<label for="txtFirstName">First Name *</label>
				<input name="txtFirstName" id="txtFirstName" value="<?php echo_value('FirstName'); ?>" />
			</li>
			<li>
				<label for="txtLastName">Last Name *</label>
				<input name="txtLastName" id="txtLastName" value="<?php echo_value('LastName'); ?>" />
			</li>
			<li>
				<label for="txtDOB">Date of Birth <em>(MM-DD-YYYY)</em></label>
				<input name="txtDOB" id="txtDOB" value="<?php echo_value('DOB'); ?>" />
			</li>
			<li>
				<label for="drpState">State *</label>
				<select name="drpState" id="drpState">
					<option value="0" style="font-style: italic">--Select One--</option>
					<?php
						foreach($aryList['State'] as $key=>$val) {
							if ($key == $_POST['drpState']) {
								echo '<option value="',$key,'" selected="selected">',htmlspecialchars($val),"</option>\n";
							}
							else {
								echo '<option value="',$key,'">',htmlspecialchars($val),"</option>\n";
							}
						}
					?>
				</select>
			</li>
			<li>
				<label for="txtComments">Comments</label>
				<textarea cols="50" rows="4" name="txtComments" id="txtComments"><?php echo_value('Comments'); ?></textarea>
			</li>
		</ul>

		<!-- SEE NOTES IN POST -->
		<ul style="margin-left: -8872px; height: 10px;">
			<li>
				<label for="URL">This field must be left blank</label>
				<input type="text" id="URL" name="URL" value="" />
			</li>
		</ul>

		<p>
			<input type="hidden" name="hidPostHash" value="<?php echo $strPostHosh; ?>" />
			<input type="submit" name="submit" value="Save Data" />
		</p>
	</form>
</body>
</html>

Re: Form submits only some info through email

Posted: Tue Jun 28, 2011 12:12 pm
by mynahbird
I am loving it! Will be playing with it today

Mahalo Nui Loa (Heartfelt Thanks) ~S~

Re: Form submits only some info through email

Posted: Wed Jun 29, 2011 3:12 am
by social_experiment
mynahbird wrote:2) Where ~ Does not go through to the emailed form. I don't know why. Can't find the error, Please Help
$Where is never defined :)

Code: Select all

<?php
$Brochure_Number=($_POST['Brochure_Number']);
$Date_Purchased=($_POST['Date_Purchased']);
$Name=($_POST['Name']); 
$Street=($_POST['Street']); 
$City=($_POST['City']); 
$Zip=($_POST['Zip']); 
$Phone=($_POST['Phone']);
$Cell=($_POST['Cell']);
$Email=($_POST['Email']);
// the line below was missing a single quote inside the square brackets.
$Sq_Ft=($_POST['Sq_Ft']);
?>
mynahbird wrote:1) Date_Purchased, what code needed to get the date printed on the brochure to appear in the email? I get it with php current date code; but am confused as to what code to receive inputed data: Month, Day, Year. Don't really want to do a pop up calendar because of conflicting codes within the page, like JSs Is their a shorter way?
Is it the current date, a date supplied by the user (not today's date)?