# HTML Contact Form



## Rutter (Dec 17, 2001)

Hi Everyone,
Wondering if anyone can offer advice I would like to setup a contact form on my website to stop me having to advertise email addresses and am not sure how I would be able to use a drop down box to change what address the form is being sent to, I presume this is possible with javascript, but is there any server side solution to this problem?

Thanks In Advance!

Rutter


----------



## namenotfound (Apr 30, 2005)

If you have PHP, you can use mail()


----------



## Sequal7 (Apr 15, 2001)

Try this form, it requires a server that uses php but you can select what email to send the form to, in a drop down box. The email only requires one change, that is the fields of the emails in the dropdown.

You can call the script page onto any existing web page as long as it's a .php extension (if its called whatever.htm, rename it whatever.php)

include it in your webapge by pasting this in the area you want the form to show

```
<? include("mail.php") ?>
```
 making sure that mail.php is in the same folder as your webpage and it will work fine.

Now onto editing the script for your emails and names.
Copy and paste this script and name it *mail.php*

Look for this line is the script

```
$form_structure = array(
```
 and immediately below it is this:

```
"selrecip|fmselect|Send to|fm_sendto|User 1|[email protected]|User 2|[email protected]|",
```
change the User1 to the first email contact name and the [email protected] to the contact email, do that to the other one too. You can add more if you need to. This is the actual part in the script on that line you modify.

```
User 1|[email protected]|User 2|[email protected]
```
To add more, you use this

```
User 3|[email protected]|
```
The full unedited script to copy;

```
<?php
session_start();

// --------------------------------
// START OF OPTIONS
// --------------------------------

// RECIPIENTS
// ----------
// One:       "onerecip|(email)"
// Multiple:  "mulrecip|(cc or bcc)|(email 1)|(email 2)  etc.. "
// Drop-down: "selrecip"  
// (the drop-down data must be added to the form structure below)

$recipients = "selrecip";

// FORM STRUCTURE
// --------------
// Please see the website for a full explanation of the structure.
// It is easy to use, but a bit too long to explain here :)

$form_structure = array(	
	"selrecip|fmselect|Send to|fm_sendto|User 1|[email protected]|User 2|[email protected]|",
	"openfieldset|fmset",
	"info|fminfofull|Send me an email...",
	"text|fmtext|Name|fm_name|32|100|true|none",
	"text|fmtext|Email|fm_email|32|100|false|email",
	"text|fmtext|Subject|fm_subject|32|100|false|none",
	"text|fmtext|Verify|fm_verify|7|5|true|none",
	"textarea|fmtextarea|Message|fm_message|6 |26 |true",
	"closefieldset"
);

// SPECIAL FIELDS
// ----------------
// This lets the script know the names of the 'special' fields
//
// VERIFICATION FIELD
// To disable verification, set this to "", and 
// remove the verification line from the form structure

$field_verification = "fm_verify";

// EMAIL HEADER FIELDS
// These are the fields that will be used to generate the header
// for the email(s). If these are set to "", the email will use
// the default values (and you will not see the user's info in
// the email header - only in the message)

$field_name = "fm_name";
$field_subject = "fm_subject";
$field_email = "fm_email";

// DROP DOWN RECIPIENT
// Only applies if you are using a drop down to select a recipient

$field_dropdownrecip = "fm_sendto";

// FORM OPTIONS
// ------------
// SHOW USER WHICH FIELDS ARE REQUIRED
//
// If enabled, this will put an asterisk next to required fields.
// (styled with .fmrequired)

$show_required = TRUE;

// MESSAGE GENERATION
// ------------------

// SUBJECT [PREFIX]
// If you ask for a subject, this will be its prefix.
// If not, this will be the complete subject line.

$subject = 'Website Contact: ';

// SHOW HEADER FIELDS IN MESSAGE
// If using name, email, and/or subject fields in the email header, 
// disabling this option will keep those fields from being shown in the 
// body of the message. (since the information will already be in the header)

$show_headers_in_message = FALSE;

// SHOW VERIFICATION CODE IN MESSAGE
// If enabled, this will show the entered code in the email.

$show_code_in_message = FALSE;

// WRAP MESSAGES
// Required to meet RFC specifications (70 characters per line).

$wrap_messages = TRUE;

// INCLUDE IP
// If enabled, adds the sender's IP and host info to the message

$include_ip = TRUE;

// LANGUAGE OPTIONS
// ----------------

// SERVER ERROR MESSAGE
// Shown when message cannot be sent (do not use html tags).

$msg_mailserver = "No connection to the mailserver. Please try again later.";

// SUCCESS MESSAGE
// Shown when message has been sent (you can use html tags).

$msg_sent = "
[B][SIZE=14]Thank you![/SIZE][/B]

Your message has been sent!

";

// FORM ERROR MESSAGE
// Shown when there is a mistake on the form 
// (do not use html tags - styled with .fmerrortitle).

$msg_error = "Error!";

// SUBMIT BUTTON
// The text for the send button (do not use html tags).

$msg_submit = "Send Email";

// --------------------------------
// END OF OPTIONS
// --------------------------------

// --------------------------------
// CSS DECLARATIONS
// --------------------------------

// It is best to put these declarations in your main style sheet
// Since it is not always proper to have CSS declarations in the middle
// of a file. :)

// In the form structure above, you can specify custom class names
// for each input field if you like.

?>

<?php

// --------------------------------
// END OF CSS DECLARATIONS
// --------------------------------

// Do not edit anything below unless you know what you are doing :)

$email_sent = FALSE;
$t_out = "";

// turn $recipients into a useable array
$recipients = explode("|", $recipients);
for ($i = 0; $i < count($recipients); $i++) {
	$recipients[$i] = trim($recipients[$i]);
}

// turn form fields into a useable array
for ($i = 0; $i < count($form_structure); $i++) {
	$form_structure[$i] = explode("|", $form_structure[$i]);
	for ($j = 0; $j < count($form_structure[$i]); $j++) {
		$form_structure[$i][$j] = trim($form_structure[$i][$j]);
	}
}

function is_valid_url($link) { 
// returns TRUE if url actually exists

	if (strpos($link, "http://") === FALSE) { $link = "http://" . $link; }
    $url_parts = @parse_url($link);
	if (empty($url_parts["host"])) return( false );
	if (!empty($url_parts["path"])) { $documentpath = $url_parts["path"]; } 
    else { $documentpath = "/"; }
	if (!empty($url_parts["query"])) { $documentpath .= "?" . $url_parts["query"]; }
	$host = $url_parts["host"];	$port = $url_parts["port"];
	if (empty($port)) $port = "80";
	$socket = @fsockopen( $host, $port, $errno, $errstr, 30 );
	if (!$socket) {	return(false); } 
    else {fwrite ($socket, "HEAD ".$documentpath." HTTP/1.0\r\nHost: $host\r\n\r\n");
	$http_response = fgets( $socket, 22 );
	if (ereg("200 OK", $http_response, $regs)) { return(true); fclose($socket);	} 
	else { return(false); } }
}

function is_valid_email($email) {
// returns TRUE if email address is valid

	$qtext = '[^\\x0d\\x22\\x5c\\x80-\\xff]';
	$dtext = '[^\\x0d\\x5b-\\x5d\\x80-\\xff]';
	$atom = '[^\\x00-\\x20\\x22\\x28\\x29\\x2c\\x2e\\x3a-\\x3c'.
		'\\x3e\\x40\\x5b-\\x5d\\x7f-\\xff]+';
	$quoted_pair = '\\x5c[\\x00-\\x7f]';
	$domain_literal = "\\x5b($dtext|$quoted_pair)*\\x5d";
	$quoted_string = "\\x22($qtext|$quoted_pair)*\\x22";
	$domain_ref = $atom;
	$sub_domain = "($domain_ref|$domain_literal)";
	$word = "($atom|$quoted_string)";
	$domain = "$sub_domain(\\x2e$sub_domain)*";
	$local_part = "$word(\\x2e$word)*";
	$addr_spec = "$local_part\\x40$domain";
	return preg_match("!^$addr_spec$!", $email) ? 1 : 0;
}

function injection_chars($s) {
// returns TRUE if 'bad' characters are found
	return (eregi("\r", $s) || eregi("\n", $s) || eregi("%0a", $s) || eregi("%0d", $s)) ? TRUE : FALSE;
}

function generate_verification() {
	srand((double)microtime()*1000000); 
	$rand = rand(0,999999999);  
	$thecode = substr(strtoupper(md5($rand)), 2, 5); 
	$thecode = str_replace("O", "A", $thecode);
	$thecode = str_replace("0", "B", $thecode);
	$_SESSION["thecode"] = $thecode;
}

function strip_colons($s) {
	return str_replace(array(':', '%3a'), " ", $s);
}

$first_load = TRUE;

if (isset($_POST["form_submitted"])) {
// if the form has been submitted

	$first_load = FALSE;

	// prepare error list
	unset($errors);

	// prepare mail variables
	$mail_message = "";
	$mail_name = "Anonymous";
	$mail_subject = $subject;
	$mail_email = '[email protected]';

	// process input
	foreach ($form_structure as $form_field) {

	switch ($form_field[0]) {

	case "text":
	case "password":

		$f_type = $form_field[0];
		$f_name = $form_field[2];
		$f_fmname = $form_field[3];
		$f_max = $form_field[5];
		$f_req = $form_field[6];
		$f_ver = $form_field[7];

		// get data
		$t = (isset($_POST[$f_fmname])) ? trim($_POST[$f_fmname]) : "";
		if (get_magic_quotes_gpc()) {
			$t = stripslashes($t);
		}

		// check for size limits
		if (strlen($t) > $f_max) {
			$errors[] = "There is a $f_max character limit for '$f_name'.";
		}

		// check for required fields
		if (($f_req == "true") && ($t == "")) {
			if ($f_fmname != $field_verification) { // has it's own check
				$errors[] = "Missing required field: '$f_name'.";
			}
		}

		// check for injection characters
		if (($f_type != "textarea") && (injection_chars($t))) {
			$errors[] = "Invalid input in '$f_name'!";
		}

		// check for valid email (if present/required)
		if (($f_ver == 'email') && ($f_req == "true" || (trim($t) != ""))) {
			if (!is_valid_email($t)) {
				$errors[] = "Invalid email address: '$f_name'";
			}
		}
		// check for valid url (if present/required)
		if (($f_ver == 'url') && ($f_req == "true" || (trim($t) != ""))) {
			if (!is_valid_url($t)) {
				$errors[] = "Invalid link: '$f_name'";
			}
		}

		// check for headers/verification fields
		if ($f_fmname == $field_name) {

			if ($t != "") {
				$mail_name = strip_colons($t);
				if ($show_headers_in_message)
					$mail_message .= $f_name . ' = ' . $t . "\n\n";
			}

		} elseif ($f_fmname == $field_subject) {

			if ($t != "") {
				$mail_subject = $subject . strip_colons($t);
				if ($show_headers_in_message)
					$mail_message .= $f_name . ' = ' . $t . "\n\n";
			}

		} elseif ($f_fmname == $field_email) {

			if ($t != "") {
				$mail_email = strip_colons($t);
				if ($show_headers_in_message)
					$mail_message .= $f_name . ' = ' . $t . "\n\n";
			}

		} elseif ($f_fmname == $field_verification) {

			if ($t == "") { 
				$errors[] = "Enter the verification code!";
			} else if (trim($_SESSION["thecode"]) == "") { 
				$errors[] = "No verification code generated!";
			} else if ($_SESSION["thecode"] != strtoupper($t)) { 
				$errors[] = "Invalid verification code!";
			} else {
				if ($show_code_in_message)
					$mail_message .= $f_name . ' = ' . $t . "\n\n";
			}

		} else {

			if ($t != "") {
				$mail_message .= $f_name . ' = ' . $t . "\n\n";
			}

		}

		break;

	case "textarea":

		$f_name = $form_field[2];
		$f_fmname = $form_field[3];
		$f_req = $form_field[6];

		// get data
		$t = (isset($_POST[$f_fmname])) ? trim($_POST[$f_fmname]) : "";
		if (get_magic_quotes_gpc()) {
			$t = stripslashes($t);
		}

		// check for required fields
		if (($f_req == "true") && ($t == "")) {
			if ($f_fmname != $field_verification) { // has it's own check
				$errors[] = "Missing required field: '$f_name'.";
			}
		}

		if ($t != "") {
			$mail_message .= $f_name . " = \n" . $t . "\n\n";
		}

		break;

	case "checkbox":

		$f_name = $form_field[2];

		$t_message = $f_name . ' =';

		$f = FALSE;
		for ($i = 3; $i < count($form_field); $i+=3) {
			$f_fmname = $form_field[$i];
			$f_caption = $form_field[$i+1];

			$t = (isset($_POST[$f_fmname])) ? trim($_POST[$f_fmname]) : "";
			if ($t == 'on') {
				$t_message .= " " . $f_caption . ","; 
				$f = TRUE;
			}
		}

		$t_message = rtrim($t_message, ',');

		if ($f) {
			$mail_message .= $t_message . "\n\n";
		}

		break;

	case "radio":

		$f_name = $form_field[2];
		$f_fmname = $form_field[3];

		$t = (isset($_POST[$f_fmname])) ? trim($_POST[$f_fmname]) : "";

		$f = FALSE;
		for ($i = 5; $i < count($form_field); $i+=2) {
			if ($t == $form_field[$i]) {
				$f = TRUE;
			}
		}

		if ($f) {
			$mail_message .= $f_name . ' = ' . $t . "\n\n";
		}

		break;

	case "select":

		$f_name = $form_field[2];
		$f_fmname = $form_field[3];

		$t_message = $f_name . ' =';

		$t = (isset($_POST[$f_fmname])) ? $_POST[$f_fmname] : "";

		foreach ((array)$t as $tt) {

			$f = FALSE;		
			for ($i = 6; $i < count($form_field); $i++) {
				if (($form_field[$i] == $tt) && (trim($tt) != "")) {
					$f = TRUE;
				}
			}
			if ($f) {
				$t_message .= ' ' . $tt . ',';
			}

		}

		$t_message = rtrim($t_message, ',');

		if ($f) {
			$mail_message .= $t_message . "\n\n";
		}

		break;

	}

	}

	// if no errors, process
	if (empty($errors)) {

		$mail_message = trim($mail_message);

		// wrap messages if set
		if ($wrap_messages) {
			$mail_message = wordwrap($mail_message, 70);
		}

		// prepare the headers
		// \r\n seems to be the best method for most servers to handle
		$ip = $_SERVER["REMOTE_ADDR"];
		$mail_header = "";
		$mail_header .= "MIME-Version: 1.0\r\n"; 
		$mail_header .= "X-Sender-IP: $ip\r\n";
		$mail_header .= "Content-Type: text/plain\r\n";
		$mail_header .= "From: " . $mail_name . " <" . $mail_email . ">";

		if ($recipients[0] == 'onerecip') {

			$mail_to = $recipients[1];

		} elseif ($recipients[0] == 'mulrecip') {

			$mail_to = $recipients[2];
			for ($i = 3; $i < count($recipients); $i++) {

				$mail_header .= "\r\n";
				if ($recipients[1] == 'cc') {
					$mail_header .= "Cc: ";
				} else {
					$mail_header .= "Bcc: ";
				}
				$mail_header .= $recipients[$i];
			}

		} elseif ($recipients[0] == 'selrecip') {

			$recip_number = (int)$_POST[$field_dropdownrecip];
			foreach ($form_structure as $form_field) {
				if ($form_field[0] == 'selrecip') {
					$j = 1;
					for ($i = 4; $i < count($form_field); $i++) {
						if (strpos($form_field[$i], "#") === 0) {
							$i++;
						}
						$i++;
						if ($recip_number == $j) {
							$mail_to = $form_field[$i];
						}
						$j++;
					}
				}
			}
		}

		// send mail, setting $email_sent to true or false

			if ($include_ip) {
				$mail_message .= "\n";
				$mail_message .= "\nHost: " . $_SERVER["HTTP_HOST"];
				$mail_message .= "\nIP: " . $_SERVER["REMOTE_ADDR"];
				$mail_message .= "\nBrowser: " . $_SERVER["HTTP_USER_AGENT"];
			}

		if (mail($mail_to, $mail_subject, $mail_message, $mail_header, "-f $mail_email")) {
			$email_sent = true; 
		} else {
			$errors[] = $msg_mailserver;
			$email_sent = false;
		}

	}

	if (isset($errors)) {

		// if there were errors, list them

		$t_out .= '';
		$t_out .= '

' . $msg_error . '

[LIST]';

		foreach ($errors as $f)
			$t_out .= '[*]' . $f . '';

		$t_out .= '[/LIST]';

	} else {

		// the message was sent, display message

		$t_out .= '';

		$t_out .= $msg_sent;

		$t_out .= '';

		generate_verification();

	}

}

if (!$email_sent) {

// SHOW FORM

generate_verification();

if (!extension_loaded("gd")) {
   $t_out .= "

[B]GD Support not detected![/B] GD is required for this script.

";
}

$t_out .= '';
$t_out .= '';

// go through fields
foreach ($form_structure as $form_field) {

	// process field types
	switch ($form_field[0]) {

	case "openfieldset":

		$f_class = $form_field[1];

		$t_out .= '';

		if (count($form_field) > 2) {

			$f_legend = $form_field[2];

			$t_out .= '' . $f_legend . '';
		}

		break;

	case "closefieldset":

		$t_out .= '';

		break;

	case "info":

		$f_class = $form_field[1];
		$f_text = $form_field[2];

		$t_out .= '' . $f_text . '';

		break;

	case "text":

		$f_class = $form_field[1];
		$f_name = $form_field[2];
		$f_fmname = $form_field[3];
		$f_size = $form_field[4];
		$f_max = $form_field[5];
		$f_req = $form_field[6];

		$t_out .= '';
		if (($f_req == "true") && ($show_required)) 
			$t_out .= '* ';
		$t_out .= $f_name . '';

		$t_out .= '';

		if ($f_fmname == $field_verification) {
			$t_out .= '[IMG]mail_verify.php[/IMG]';
		}

		$t_out .= '
';

		break;

 	case "password":

		$f_class = $form_field[1];
		$f_name = $form_field[2];
		$f_fmname = $form_field[3];
		$f_size = $form_field[4];
		$f_max = $form_field[5];
		$f_req = $form_field[6];

		$t_out .= '';
		if (($f_req == "true") && ($show_required)) 
			$t_out .= '* ';
		$t_out .= $f_name . '';

		$t_out .= '
';

		break;

	case "textarea":

		$f_class = $form_field[1];
		$f_name = $form_field[2];
		$f_fmname = $form_field[3];
		$f_rows = $form_field[4];
		$f_cols = $form_field[5];
		$f_req = $form_field[6];

		$t_out .= '';
		if (($f_req == "true") && ($show_required)) 
			$t_out .= '* ';
		$t_out .= $f_name . '';

		$t_out .= '';

		if (isset($_POST[$f_fmname])) {
			if ($f_fmname != $field_verification) {
				$t_out .= htmlspecialchars($_POST[$f_fmname]);
			}
		}

		$t_out .= '
';

		break;

	case "checkbox":

		$f_class = $form_field[1];
		$f_name = $form_field[2];

		$t_out .= '' . $f_name . '';

		for ($i = 3; $i < count($form_field)-1; $i+=3) {
			if ($i > 3) {
				$t_out .= ' ';
			}

			$f_fmname = $form_field[$i];
			$f_caption = $form_field[$i+1];
			$f_checked = $form_field[$i+2];

			$t_out .= '';
			$t_out .= '' . $f_caption . ' 
';
		}

		break;

	case "radio":

		$f_class = $form_field[1];
		$f_name = $form_field[2];
		$f_fmname = $form_field[3];
		$f_def = $form_field[4];

		$t_out .= '' . $f_name . '';

		$j = 1;
		for ($i = 5; $i < count($form_field); $i+=2) {

			$f_value = $form_field[$i];
			$f_caption = $form_field[$i+1];

			if ($i > 5) {
				$t_out .= ' ';
			}
			$t_out .= '';
			$t_out .= '' . $f_caption . ' 
';

			$j++;
		}

		break;

	case "select":

		$f_class = $form_field[1];
		$f_name = $form_field[2];
		$f_fmname = $form_field[3];
		$f_mul = $form_field[4];

		$t_out .= '' . $f_name . '';
		$t_out .= '';

		$grp_count = 0;
		for ($i = 5; $i < count($form_field)-1; $i++) {

			if (strpos($form_field[$i], "#") === 0) {

				if ($grp_count > 0) {
					$t_out .= "";
				}

				$t_out .= '';

				$grp_count++;
				$i++;
			}

			$t_out .= ' ' . $form_field[$i+1] . '';

			$i++;

		}

		if ($grp_count > 0) {
			$t_out .= "";
		}
		$t_out .= '
';

		break;

	case "selrecip":

		$f_class = $form_field[1];
		$f_name = $form_field[2];
		$f_fmname = $form_field[3];

		$t_out .= '' . $f_name . '';
		$t_out .= '';

		$j = 1;
		$grp_count = 0;
		for ($i = 4; $i < count($form_field)-1; $i++) {

			if (strpos($form_field[$i], "#") === 0) {

				if ($grp_count > 0) {
					$t_out .= "";
				}

				$t_out .= '';

				$grp_count++;
				$i++;
			}

			$t_out .= ' ' . $form_field[$i] . '';

			$i++;
			$j++;
		}

		if ($grp_count > 0) {
			$t_out .= "";
		}
		$t_out .= '
';

		break;

	}	
}

$t_out .= '';

$t_out .= '';

$t_out .= '';

$t_out .= '';

}

echo $t_out;

?>
```
Then, use this as the anti-spam confirmation part, it checks for a code entered to ensure that person is filling out the form, not a spambot or webcrawler. Name this file *mail_verify.php*

```
<?php
session_start();

header("Content-type: image/png");
$image = imagecreate(60,20);
$background_color = imagecolorallocate ($image, 219, 236, 255);
$blue = imagecolorallocate($image, 0, 90, 190);
imagestring($image,5,8,2,$_SESSION["thecode"],$blue);
imagepng($image);
imagedestroy($image);
?>
```
Here it is in action for a limited time only though since I don't want it abused.


----------

