Spam Honey Pot trap

#1

A complete newcomer to Javascript and PHP... I have now spent more time on the contact form than the rest of entire site put together!!!!

I have a working (so far as I know) contact form. However it has zero in the way of security and came across a honeypot trap at:http://devgrow.com/simple-php-honey-pot/

I have my own contact form with Javascript validation and would like to add the Honey Pot part only. I have my own Javascript error messages so what parts of the example PHP would I need to integrate and whats parts would I leave out?

Below is the Honey Pot example and below that is my contact form.

I think after I finish this contact form I'm going to start to study the various books on Javascript & PHP I bought recently!

Honey Pot Example:

<html>
<head>
<title>Honey pot test</title>
<!-- This example and tutorial can be found at http://devgrow.com/simple-php-honey-pot -->
<style>
	/* Optional Styling: */
	body { background: #fafafa; font-size: 13px; font-family: Verdana; padding: 40px; }
	fieldset { width: 280px; background: #fff; padding: 10px; display: block; }
	legend { font-size: 18px; margin: 0; }
	input, textarea { margin: 0; padding: 3px; border: 1px solid #aaa; -moz-border-radius: 3px; -webkit-border-radius: 3px; border-radius: 3px; width: 278px }
	label { width: 100%; font-weight: bold; float: left; }
	.submit { background: #444; color: #fff; width: inherit; border: none; padding: 5 10px; cursor: pointer; } .submit:hover { background: #000; }
	.msg { padding: 10px; border: 1px solid #ccc; background: #fff; width: 285px; margin: 0 0 20px; }
	.msg.success { border-color: #86a62f; background: #faffec; }
	.msg.error { border-color: #cd5a5a; background: #fff7f7; }
	
	/* Required for Honey Pot: */
	.robotic { display: none; }
</style>
<script type="text/javascript">
	function showpot() {
		document.getElementById("pot").className = "";
		return false;
	}
</script>
</head>
<body>
<font color='"#FF0000"'><?php
	if($_POST){
		$to = 'your-email-here@gmail.com';
		$subject = 'Contact Form Submission';
		$from_name = $_POST['name'];
		$from_email = $_POST['email'];
		$message = $_POST['message'];
		$robotest = $_POST['robotest'];
		if($robotest)
			$error = "You are a gutless robot.";
		else{
			if($from_name && $from_email && $message){
				$header = "From: $from_name <$from_email>";
				if(mail($to, $subject, $message, $header))
					$success = "You are human and your message was sent!";
				else
					$error = "You are human but there was a problem sending the e-mail.";
			}else
				$error = "All fields are required.";
		}
		if($error)
			echo '<div class="msg error">'.$error.'</div>';
		elseif($success)
			echo '<div class="msg success">'.$success.'</div>';
	}
?></font>
<form method="post" action="">
	<fieldset>
		<legend>Contact Me</legend>
		<p>
			<label>Name:</label>
			<input name="name" type="text" id="name" />
		</p>
		<p>
			<label>E-mail:</label>
			<input name="email" type="text" id="email" />
		</p>
		<p>
			<label>Message:</label>
			<textarea name="message" id="message"></textarea>
		</p>
		<!-- The following field is for robots only, invisible to humans: -->
		<p class="robotic" id="pot">
			<label>If you're human leave this blank:</label>
			<input name="robotest" type="text" id="robotest" class="robotest" />
		</p>
		<p>
			<input type="submit" value="Send Message" class="submit" />
		</p>
	</fieldset>
</form>
<br />
<a href="#" onClick="showpot();">Show honey pot field?</a><br />
<a href="http://devgrow.com/simple-php-honey-pot/">View Tutorial</a>
</body>
</html>

My Contact Form - Work in Progress :

<!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>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Pete's Contact Form with jQuery Validation</title>
<script type="text/javascript" src="js/messages.js"></script>

<style type="text/css">

* {font-family: Arial, Helvetica, sans-serif;}
	
body { background-color: #999;}
.form label { font-size: 90%;}
.required_notification { font-size: 80%;}
	

 /*CONTACT FORM - LEFT DIV*/
#input_wrapper { width: 500px;
				padding: 10px 20px 20px 20px;
				background: #555;
             	background: -moz-linear-gradient(top, #444 0%, #666 50%); /* firefox */
	            background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #444), color-stop(50%, #666)); /* webkit */
	            border-radius: 3px;
	           -moz-border-radius: 3px;
	           -webkit-border-radius: 3px;
	           -webkit-box-shadow: 0px 2px 2px #333333;
	            box-shadow: 0px 2px 2px #333333;}

/*Padding/margins/borders/outlines settings*/
input, textarea {
	margin: 0;
	padding: 0;
	border: 0;
	outline: none;}
	
/*Border Bottom*/		
.form li:first-child, .contact_form li:last-child {
	border-bottom:1px solid #CCC;}
/*Border Bottom*/	

/*Padding/margins/borders/outlines*/


/*No glowing edges to inputs!!!*/
*:focus {outline: none;}
/*No glowing edges to inputs!!!*/
	
/*Header*/	
.form h3 {
	margin:0px;
	display: inline;}
	
.required_notification {
	color: #F06; /*#27AECF*/
	margin:5px 0 0 0;
	display:inline;
	float:right;}
/*Header*/	


/*Contact form labels*/
.form ul {
    width:500px;
    list-style-type:none;
	list-style-position:outside;
	margin:0px;
	padding:0px;}

.form li{
	color:#FFF;
	padding:10px;
	border-bottom:1px solid #999;
	position:relative;}
	
	
.form label {
	width:80px;
	margin-top: 2px;
	display:inline-block;
	float:left;
	padding:3px;}
	
#msg {display:none;
      font-size:75%;
      position:absolute;
	  z-index:200;
	  background: url(images/msg_arrow.gif) left center no-repeat;
	  padding-left:7px;}
	
#msgcontent {display:block;
              background: #D6D6D6;
			  border:2px solid #F06;
			  border-left:none;
			  padding:5px;
			  min-width:192px;
			  max-width:192px;}
	
			
/*Contact form labels*/


/*Contact form inputs*/
.form input:focus, .form textarea:focus { background-color: #EBEBEB;}

/*Contact form text fields*/
.form input {
    font-family:Arial, Helvetica, sans-serif;
	font-size: 80%;
 	background-color: #D6D6D6;
	/*border:1px solid #aaa;*/
	height:20px;
	width:180px;
	margin: 0px;
	padding:2px 5px;
	border-radius: 2px;
	-moz-border-radius: 2px;
	-webkit-border-radius: 2px;}
/*Contact form text fields*/


/*Contact textarea*/
.form textarea { font-family:Arial, Helvetica, sans-serif;
                         font-size: 80%;
                         width: 240px;
                         height: 100px;
                         padding: 5px 5px;
                         background-color: #D6D6D6;/*padding-right:30px;*/
		                 /*border:1px solid #aaa;*/
		                 border-radius: 2px;
                     	 -moz-border-radius: 2px;
	                     -webkit-border-radius: 2px;}
/*Contact textarea*/	
					
/*Contact form inputs*/


/*input/textarea placeholder text*/
input::-webkit-input-placeholder { color: #777;}

input:-moz-placeholder { color: #777;}

::-webkit-input-placeholder { color: #777;}
	
:-moz-placeholder { color: #777;}
/*input/textarea placeholder text*/

	
/*sprite email button*/	

input.submit { width: 148px;
               height: 40px;
	           margin-left: 190px;
	           background-position: 0px 0px;
	           background-color: transparent; /* or #666*/
	           background-image: url(images/email_sprite.png);
	           /*background:transparent url(images/email_sprite.png);*/
	           text-indent: -9999px;
	           display: inline-block;
	           border:none;
			   outline:none;}
			
input.submit:hover { background-position: 0px -40px;}

input.submit:active { background-position: 0px -80px;}

/*sprite email button*/		

/*CONTACT FORM - LEFT DIV*/	
</style>

</head>

<body>
<div id="input_wrapper">
      <form name="form" id="form" class="form" action="" onsubmit="return validate(this)" method="post">

        <ul>

        <li>
             <h3>Contact Us</h3>
             <span class="required_notification">* Denotes Required Field</span>
        </li>

        <li>
          <label for="name">Name:</label>
          <input type="text" name="name" id="name" placeholder="Enter your full name *" />
        </li>

        <li>
          <label for="email">Email:</label>
          <input type="text" name="email" id="email" placeholder="Enter your email address *" />
        </li>

        <li>
          <label for="telephone">Phone:</label>
          <input type="text" name="landline" id="landline" placeholder="Enter your landline number *" />
        </li>

        <li>
          <label for="mobile">Mobile:</label>
          <input type="text" name="mobile" id="mobile" placeholder="Enter your mobile number *" />
       </li>

        <li>
          <label for="message">Message:</label>
          <textarea id="message" name="message" placeholder="Enter your message here...*"></textarea>
       </li>

       <li>
        <input type="submit" value="submit" class="submit"/>
        </li>
       </ul>
      </form>
    </div>
</body>
</html>

#2

Hi there,

To implement this technique you need to do the following:

Add this to your HTML:

<!-- The following field is for robots only, invisible to humans: -->
<li class="robotic" id="pot">
  <label for="robotest">If you're human leave this blank:</label>
  <input name="robotest" id="robotest" class="robotest" type="text" />
</li>

Add this to your CSS:

.robotic { display:none; }

What you add to your PHP will depend on how what you already have.
Basically, we can break it down into the following:

$robotest = $_POST['robotest'];

This fetches whichever value was submitted in the robotest field and stores it in a variable named $robotest

if($robotest){
  we are dealing with a bot
else{
  we are dealing with a human
 }

This will check to see if there is anything stored in the variable $robotest.
In his example the author just adds an error to the $error variable to display.
You could also have the form just fall over and die.

Hope that helps.

#3

So something like this? If I take anything else out it I get syntax errors. My contact form has validation except for a success message. So I could keep the PHP as below?

Having no experience in Javascript & PHP I find it all frustrating! So don't be afraid to explain t in a way a complete dummy could understand! ...And Happy New Year!

<?php
	if($_POST){
		$robotest = $_POST['robotest'];
		if($robotest)
			$error = "die robot.";
		else{
			$success = "You are human and your message was sent!";
				
		}
		if($success)
			echo '<div class="msg success">'.$success.'</div>';
	}
?>

Alternatively to keep things tidy could the above PHP be integrated in to my current validation form below?

// form validation function //
function validate(form) {
  var name = form.name.value;
  var email = form.email.value;
  var message = form.message.value;
  var nameRegex = /^[a-zA-Z]+(([\\'\\,\\.\\- ][a-zA-Z ])?[a-zA-Z]*)*$/;
  var emailRegex = /^[\\w-\\.]+@([\\w-]+\\.)+[\\w-]{2,4}$/;
  var messageRegex = new RegExp(/<\\/?\\w+((\\s+\\w+(\\s*=\\s*(?:".*?"|'.*?'|[^'">\\s]+))?)+\\s*|\\s*)\\/?>/gim);
  if(name == "") {
    inlineMsg('name','Please enter your name!',2);
    return false;
  }
  if(!name.match(nameRegex)) {
    inlineMsg('name','Please enter an invalid name!',2);
    return false;
  }
  if(email == "") {
    inlineMsg('email','<strong>Error!</strong> Please enter your email!',2);
    return false;
  }
  if(!email.match(emailRegex)) {
    inlineMsg('email','<strong>Error!</strong> This email is invalid!',2);
    return false;
  }
  if(message == "") {
    inlineMsg('message','Please enter your message!');
    return false;
  }
  if(message.match(messageRegex)) {
    inlineMsg('message','This message is invalid!');
    return false;
  }
  return true;
}

// START OF MESSAGE SCRIPT //

var MSGTIMER = 20;
var MSGSPEED = 5;
var MSGOFFSET = 3;
var MSGHIDE = 3;

// build out the divs, set attributes and call the fade function //
function inlineMsg(target,string,autohide) {
  var msg;
  var msgcontent;
  if(!document.getElementById('msg')) {
    msg = document.createElement('div');
    msg.id = 'msg';
    msgcontent = document.createElement('div');
    msgcontent.id = 'msgcontent';
    document.body.appendChild(msg);
    msg.appendChild(msgcontent);
    msg.style.filter = 'alpha(opacity=0)';
    msg.style.opacity = 0;
    msg.alpha = 0;
  } else {
    msg = document.getElementById('msg');
    msgcontent = document.getElementById('msgcontent');
  }
  msgcontent.innerHTML = string;
  msg.style.display = 'block';
  var msgheight = msg.offsetHeight;
  var targetdiv = document.getElementById(target);
  targetdiv.focus();
  var targetheight = targetdiv.offsetHeight;
  var targetwidth = targetdiv.offsetWidth;
  var topposition = topPosition(targetdiv) - ((msgheight - targetheight) / 2);
  var leftposition = leftPosition(targetdiv) + targetwidth + MSGOFFSET;
  msg.style.top = topposition + 'px';
  msg.style.left = leftposition + 'px';
  clearInterval(msg.timer);
  msg.timer = setInterval("fadeMsg(1)", MSGTIMER);
  if(!autohide) {
    autohide = MSGHIDE;  
  }
  window.setTimeout("hideMsg()", (autohide * 1000));
}

// hide the form alert //
function hideMsg(msg) {
  var msg = document.getElementById('msg');
  if(!msg.timer) {
    msg.timer = setInterval("fadeMsg(0)", MSGTIMER);
  }
}

// face the message box //
function fadeMsg(flag) {
  if(flag == null) {
    flag = 1;
  }
  var msg = document.getElementById('msg');
  var value;
  if(flag == 1) {
    value = msg.alpha + MSGSPEED;
  } else {
    value = msg.alpha - MSGSPEED;
  }
  msg.alpha = value;
  msg.style.opacity = (value / 100);
  msg.style.filter = 'alpha(opacity=' + value + ')';
  if(value >= 99) {
    clearInterval(msg.timer);
    msg.timer = null;
  } else if(value <= 1) {
    msg.style.display = "none";
    clearInterval(msg.timer);
  }
}

// calculate the position of the element in relation to the left of the browser //
function leftPosition(target) {
  var left = 0;
  if(target.offsetParent) {
    while(1) {
      left += target.offsetLeft;
      if(!target.offsetParent) {
        break;
      }
      target = target.offsetParent;
    }
  } else if(target.x) {
    left += target.x;
  }
  return left;
}

// calculate the position of the element in relation to the top of the browser window //
function topPosition(target) {
  var top = 0;
  if(target.offsetParent) {
    while(1) {
      top += target.offsetTop;
      if(!target.offsetParent) {
        break;
      }
      target = target.offsetParent;
    }
  } else if(target.y) {
    top += target.y;
  }
  return top;
}

// preload the arrow //
if(document.images) {
  arrow = new Image(7,80); 
  arrow.src = "images/msg_arrow.gif"; 
}
#4

Hi there,

The PHP code looks fine.
I wouldn't try and integrate it into the JavaScript, rather into your existing PHP code.

Could you post the contents of the PHP script to which your form is submitted.

#5

$POST always exists; it's a superglobal. Try checking for a specific value of $POST, not for the array itself.

#6

Showing up my ignorance again here!

Currently it only has the Javascript validation and no PHP. What other PHP do I need?

On a positive note I've set up MAMP!

#7

Hi,

JavaScript validation is fine for most cases, but it is implemented client-side, i.e. in your users' browser.
This means that if I turn JavaScript off at my end, I can completely bypass your validation and the form will always submit regardless of what I enter.

PHP validation on the other hand takes place on a remote server and cannot be bypassed by anyone.
It is also a good idea to use PHP (or any other server-side language) to sanitize any user input before processing it, especially if you are saving user input to a data base.

Before we get into the best way for you to implement this, I'm curious: how are you actually sending your mail, as this is not something you can do using JavaScript alone.

Let me know and I'm sure we can get to the bottom of this.

#8

... yes I see what you mean. So in my contact forms HTML i need to link in a PHP document like this:

form name="form" id="form" class="form" action="<font color='"#FF0000"'>form_to_email.php</font>" onsubmit="return validate(this)" method="post">

Basically I haven't got the necessary PHP skills to create such a document! frowning

#9

Hi there,

No problem. I can help you make the PHP script to power the form.
Client side validation is still valuable, as it makes the form feel snappier and is nicer for your users. You don't have to bin your work so far!

I'll put something together, using your form above as a template and incorporating the spam trap. Then I'll get back to you tomorrow (it's late here and I'm turning in soon).

Edit: One question. You do have access to a PHP environment with a mail server, don't you? Most web hosting companies provide this. The sending mail part won't work locally (i.e. MAMP) without further configuration.

#10

Meh, who needs sleep?

Here's your contact form:

<!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>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title>Pete's Contact Form with jQuery Validation</title>
    <script type="text/javascript" src="js/messages.js"></script>
    <style type="text/css">
      * {font-family: Arial, Helvetica, sans-serif;}
      body { background-color: #999;}
      .form label { font-size: 90%;} 
      .required_notification { font-size: 80%;} 
      
      /*CONTACT FORM - LEFT DIV*/
      #input_wrapper { width: 500px;
      padding: 10px 20px 20px 20px; 
      background: #555;
      background: -moz-linear-gradient(top, #444 0%, #666 50%); /* firefox */
      background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #444), color-stop(50%, #666)); /* webkit */
      border-radius: 3px;
      -moz-border-radius: 3px;
      -webkit-border-radius: 3px;
      -webkit-box-shadow: 0px 2px 2px #333333;
      box-shadow: 0px 2px 2px #333333;}
      
      /*Padding/margins/borders/outlines settings*/
      input, textarea {
      margin: 0;
      padding: 0;
      border: 0;
      outline: none;}
      
      /*Border Bottom*/    
      .form li:first-child, .contact_form li:last-child {
      border-bottom:1px solid #CCC;}
      /*Border Bottom*/  
      
      /*Padding/margins/borders/outlines*/
      
      /*No glowing edges to inputs!!!*/
      *:focus {outline: none;}
      /*No glowing edges to inputs!!!*/
      
      /*Header*/  
      .form h3 {
      margin:0px;
      display: inline;}
      
      .required_notification {
      color: #F06; /*#27AECF*/
      margin:5px 0 0 0; 
      display:inline;
      float:right;}
      /*Header*/  
      
      /*Contact form labels*/
      .form ul {
      width:500px;
      list-style-type:none;
      list-style-position:outside;
      margin:0px;
      padding:0px;}
      
      .form li{
      color:#FFF;
      padding:10px; 
      border-bottom:1px solid #999;
      position:relative;}
      
      .form label {
      width:80px;
      margin-top: 2px;
      display:inline-block;
      float:left;
      padding:3px;}
      
      #msg {display:none; 
      font-size:75%;
      position:absolute; 
      z-index:200; 
      background: url(images/msg_arrow.gif) left center no-repeat; 
      padding-left:7px;}
      
      #msgcontent {display:block; 
      background: #D6D6D6; 
      border:2px solid #F06; 
      border-left:none; 
      padding:5px; 
      min-width:192px; 
      max-width:192px;}
      
      /*Contact form labels*/
      
      /*Contact form inputs*/
      .form input:focus, .form textarea:focus { background-color: #EBEBEB;}
      
      /*Contact form text fields*/
      .form input { 
      font-family:Arial, Helvetica, sans-serif;
      font-size: 80%;
      background-color: #D6D6D6;
      /*border:1px solid #aaa;*/ 
      height:20px; 
      width:180px; 
      margin: 0px;
      padding:2px 5px;
      border-radius: 2px;
      -moz-border-radius: 2px;
      -webkit-border-radius: 2px;}
      /*Contact form text fields*/
      
      /*Contact textarea*/
      .form textarea { font-family:Arial, Helvetica, sans-serif; 
      font-size: 80%;
      width: 240px;
      height: 100px;
      padding: 5px 5px;
      background-color: #D6D6D6;/*padding-right:30px;*/
      /*border:1px solid #aaa;*/
      border-radius: 2px;
      -moz-border-radius: 2px;
      -webkit-border-radius: 2px;}
      /*Contact textarea*/  
      
      /*Contact form inputs*/
      
      /*input/textarea placeholder text*/
      input::-webkit-input-placeholder { color: #777;}
      input:-moz-placeholder { color: #777;}
      ::-webkit-input-placeholder { color: #777;}
      :-moz-placeholder { color: #777;}
      /*input/textarea placeholder text*/
      
      /*sprite email button*/  
      input.submit { width: 148px; 
      height: 40px;
      margin-left: 190px;
      background-position: 0px 0px;
      background-color: transparent; /* or #666*/
      background-image: url(images/email_sprite.png);
      /*background:transparent url(images/email_sprite.png);*/
      text-indent: -9999px;
      display: inline-block; 
      border:none;
      outline:none;} 
      
      input.submit:hover { background-position: 0px -40px;}
      input.submit:active { background-position: 0px -80px;}
      /*sprite email button*/    
      
      .robotic { display:none; }
      
      /*CONTACT FORM - LEFT DIV*/  
    </style>
  </head>
  
  <body>
    <div id="input_wrapper">
      <form name="form" id="form" class="form" action="myScript.php" onsubmit="return validate(this)" method="post">
        <ul>
          <li>
            <h3>Contact Us</h3>
            <span class="required_notification">* Denotes Required Field</span>
          </li>
          <li>
            <label for="name">Name:</label>
            <input type="text" name="name" id="name" placeholder="Enter your full name *" />
          </li>
          <li>
            <label for="email">Email:</label>
            <input type="text" name="email" id="email" placeholder="Enter your email address *" />
          </li>
          <li>
            <label for="telephone">Phone:</label>
            <input type="text" name="landline" id="landline" placeholder="Enter your landline number *" />
          </li>  
          <li>  
            <label for="mobile">Mobile:</label>
            <input type="text" name="mobile" id="mobile" placeholder="Enter your mobile number *" />
          </li> 
          <li>  
            <label for="message">Message:</label>
            <textarea id="message" name="message" placeholder="Enter your message here...*"></textarea>     
          </li>
          
          <!-- The following field is for robots only, invisible to humans: -->
          <li class="robotic">
            <label for="robotest">If you're human leave this blank:</label>
            <input type="text" id="robotest" name="robotest" class="robotest" />
          </li>  
                  
          <li>
            <input type="submit" value="submit" class="submit"/>
          </li>
        </ul>
      </form>
    </div>
    
    <script>
      // form validation function //
      function validate(form) {
        var name = form.name.value;
        var email = form.email.value;
        var message = form.message.value;
        var nameRegex = /^[a-zA-Z]+(([\\'\\,\\.\\- ][a-zA-Z ])?[a-zA-Z]*)*$/;
        var emailRegex = /^[\\w-\\.]+@([\\w-]+\\.)+[\\w-]{2,4}$/;
        var messageRegex = new RegExp(/<\\/?\\w+((\\s+\\w+(\\s*=\\s*(?:".*?"|'.*?'|[^'">\\s]+))?)+\\s*|\\s*)\\/?>/gim);
        if(name == "") {
          inlineMsg('name','Please enter your name!',2);
          return false;
        }
        if(!name.match(nameRegex)) {
          inlineMsg('name','Please enter an invalid name!',2);
          return false;
        }
        if(email == "") {
          inlineMsg('email','<strong>Error!</strong> Please enter your email!',2);
          return false;
        }
        if(!email.match(emailRegex)) {
          inlineMsg('email','<strong>Error!</strong> This email is invalid!',2);
          return false;
        }
        if(message == "") {
          inlineMsg('message','Please enter your message!');
          return false;
        }
        if(message.match(messageRegex)) {
          inlineMsg('message','This message is invalid!');
          return false;
        }
        return true;
      }
      
      // START OF MESSAGE SCRIPT //
      
      var MSGTIMER = 20;
      var MSGSPEED = 5;
      var MSGOFFSET = 3;
      var MSGHIDE = 3;
      
      // build out the divs, set attributes and call the fade function //
      function inlineMsg(target,string,autohide) {
        var msg;
        var msgcontent;
        if(!document.getElementById('msg')) {
          msg = document.createElement('div');
          msg.id = 'msg';
          msgcontent = document.createElement('div');
          msgcontent.id = 'msgcontent';
          document.body.appendChild(msg);
          msg.appendChild(msgcontent);
          msg.style.filter = 'alpha(opacity=0)';
          msg.style.opacity = 0;
          msg.alpha = 0;
        } else {
          msg = document.getElementById('msg');
          msgcontent = document.getElementById('msgcontent');
        }
        msgcontent.innerHTML = string;
        msg.style.display = 'block';
        var msgheight = msg.offsetHeight;
        var targetdiv = document.getElementById(target);
        targetdiv.focus();
        var targetheight = targetdiv.offsetHeight;
        var targetwidth = targetdiv.offsetWidth;
        var topposition = topPosition(targetdiv) - ((msgheight - targetheight) / 2);
        var leftposition = leftPosition(targetdiv) + targetwidth + MSGOFFSET;
        msg.style.top = topposition + 'px';
        msg.style.left = leftposition + 'px';
        clearInterval(msg.timer);
        msg.timer = setInterval("fadeMsg(1)", MSGTIMER);
        if(!autohide) {
          autohide = MSGHIDE;  
        }
        window.setTimeout("hideMsg()", (autohide * 1000));
      }
      
      // hide the form alert //
      function hideMsg(msg) {
        var msg = document.getElementById('msg');
        if(!msg.timer) {
          msg.timer = setInterval("fadeMsg(0)", MSGTIMER);
        }
      }
      
      // face the message box //
      function fadeMsg(flag) {
        if(flag == null) {
          flag = 1;
        }
        var msg = document.getElementById('msg');
        var value;
        if(flag == 1) {
          value = msg.alpha + MSGSPEED;
        } else {
          value = msg.alpha - MSGSPEED;
        }
        msg.alpha = value;
        msg.style.opacity = (value / 100);
        msg.style.filter = 'alpha(opacity=' + value + ')';
        if(value >= 99) {
          clearInterval(msg.timer);
          msg.timer = null;
        } else if(value <= 1) {
          msg.style.display = "none";
          clearInterval(msg.timer);
        }
      }
      
      // calculate the position of the element in relation to the left of the browser //
      function leftPosition(target) {
        var left = 0;
        if(target.offsetParent) {
          while(1) {
            left += target.offsetLeft;
            if(!target.offsetParent) {
              break;
            }
            target = target.offsetParent;
          }
        } else if(target.x) {
          left += target.x;
        }
        return left;
      }
      
      // calculate the position of the element in relation to the top of the browser window //
      function topPosition(target) {
        var top = 0;
        if(target.offsetParent) {
          while(1) {
            top += target.offsetTop;
            if(!target.offsetParent) {
              break;
            }
            target = target.offsetParent;
          }
        } else if(target.y) {
          top += target.y;
        }
        return top;
      }
      
      // preload the arrow //
      if(document.images) {
        arrow = new Image(7,80); 
        arrow.src = "images/msg_arrow.gif"; 
      }
    </script>
  </body>
</html>

And here's the script it should submit to (currently named myScript.php):

<?php
  $name   = strip_tags($_POST['name']);
  $email  = strip_tags($_POST['email']);
  $landline  = $_POST['landline'];
  $mobile  = $_POST['mobile'];
  $message = strip_tags($_POST['message']);
  $robotest = $_POST['robotest']; 
      
  if($robotest){
    echo "We think you're a bot!";
    exit;
  }else{
    if (empty($name)){
      $error .= "You didn't enter a name <br />";
    }
    
    if (empty($email)){
      $error .= "You didn't enter an email address <br />";
    } elseif (!eregi("^[_a-z0-9-]+(\\.[_a-z0-9-]+)*@[a-z0-9-]+(\\.[a-z0-9-]+)*(\\.[a-z]{2,})\\.?$", $email)){
      $error .= "The email address appears to be invalid <br />";  
    }
    
    if (empty($landline)){
      $error .= "You didn't enter a landline number <br />";
    } elseif (!eregi("^[0-9()+\\s-]+$", $landline)){
      $error .= "The landline number can only contain digits, spaces, brackets, plus or minus <br />";  
    }
    
    if (empty($mobile)){
      $error .= "You didn't enter a mobile number <br />";
    } elseif (!eregi("^[0-9()+\\s-]+$", $mobile)){
      $error .= "The mobile number can only contain digits, spaces, brackets, plus or minus <br />";  
    }
    
    if (empty($message)){
      $error .= "You didn't enter a message <br />";
    }
  }  
 
  if (empty($error)) {
    $newLine = chr(13).chr(10);
    $adress = "your email address here";
    $subject = "Message from contact form";
    $from = "From: Contact Form <noreply@yourdomain.com>";
    $date = "Date: ".date("j.n.Y").$newLine;
    $time = "Time: ".date("H:i").$newLine;
    $sender = "From: ".$name." <".$email.">".$newLine;
    $divider ="-------------------".$newLine.$newLine;
    $text = $date.$time.$sender.$divider.$message;
    mail($adress, $subject, $text, $from);
    header("location: http://www.sitepoint.com");
  } else {
    echo $error;
    echo "<p><strong>Please use your browser's back button and rectify this!</strong></p>";
    exit;
  }
?>

Be sure to enter your correct email address and other details at the end of the script.
You can also change the url specified in header() so that the form redirects to a page of your choosing upon successful submission.

If you have any questions, just let me know.

#11

Indeed who needs sleep! Thanks for all your help we are almost there!

I gave it a test on MAMP and I managed to send myself a test message. No access to a PHP environment as yet as the website owner can't get his act together and send me the login details! Which reminds me I need to download Transmit.

A few final things which i'd like to resolve so I can finish the site, move on, and start actually spending my time learning Javascript & PHP. Once its done I'll post it up for evaluation.

  • On submitting the form I'm directed to a blank page with http://localhost:8888/myScript.php in the URL. On submit I would like to stay on the same page and receive a success message next to the submit button (see the attached image)
  • The email I get from the test message displays the message only, no name or phone numbers
  • The mobile phone needs to be changed to non-required field.... I'll probably delete something vital!

Currently experimenting with the PHP below to get a success! message on submit. I can just about style the positioning with CSS. Mixed success so far though because its late and I'm sleepy!

<?php
	if($_POST){
		$robotest = $_POST['robotest'];
		if($robotest)
			$error = "die robot.";
		else{
			$success = "You are human and your message was sent!";
				
		}
		if($success)
			echo '<div class="msg success">'.$success.'</div>';
	}
?>
#12

I am sorry, but no one should ever use that code without updating the validation section.

You can insert additional headers without a problem, meaning I can use the contact form as my own spam tool.

Take a look on this for more information:
http://www.securephpwiki.com/index.php/Email_Injection

#13

@TheRedDevil ;

Thank you for pointing this out in a constructive manner.
Of course, you are correct.

I've reworked the PHP script to include proper validation and have tidied everything else up a bit:

<?php
  $name = filter_var($_POST['name'],FILTER_SANITIZE_STRING);
  $email = filter_var($_POST['email'],FILTER_SANITIZE_STRING, FILTER_VALIDATE_EMAIL);
  $landline = filter_var($_POST['landline'], FILTER_SANITIZE_STRING);
  $mobile = filter_var($_POST['mobile'], FILTER_SANITIZE_STRING);
  $message = filter_var($_POST['message'],FILTER_SANITIZE_STRING);
  $robotest = $_POST['robotest']; 
      
  if($robotest){
    exit("Sorry, we think you're a bot!");
  }
  
  if (empty($name)){
    $error .= "You didn't enter a name <br />";
  }
  
  if (empty($email)){
    $error .= "You didn't enter an email address <br />";
  } elseif (!eregi("^[_a-z0-9-]+(\\.[_a-z0-9-]+)*@[a-z0-9-]+(\\.[a-z0-9-]+)*(\\.[a-z]{2,})\\.?$", $email)){
    $error .= "The email address appears to be invalid <br />";  
  }
  
  if (empty($landline)){
    $error .= "You didn't enter a landline number <br />";
  } elseif (!eregi("^[0-9()+\\s-]+$", $landline)){
    $error .= "The landline number can only contain digits, spaces, brackets, plus or minus <br />";  
  }
  
  if (empty($mobile)){
    $error .= "You didn't enter a mobile number <br />";
  } elseif (!eregi("^[0-9()+\\s-]+$", $mobile)){
    $error .= "The mobile number can only contain digits, spaces, brackets, plus or minus <br />";  
  }
  
  if (empty($message)){
    $error .= "You didn't enter a message <br />";
  }
  
  if (empty($error)) {
    $toaddress = "your email address here";
    $fromaddress = "From:". $email;
    
    $mailcontent = "Name: ". $name. "\
".
                   "Email: ". $email. "\
\
".
                   $message;
                   
    mail($toaddress, "Website Contact Form", $mailcontent, $fromaddress);
    header("location: http://www.sitepoint.com");
  } else {
    echo $error;
    echo "<p><strong>Please use your browser's back button and rectify this!</strong></p>";
    exit();
  }
?>

If you can see anything I've missed, then please let me know.

#14

Me, this morning! smile

Ok, I didn't realize that worked.
I normally use xampp and you have to set up a mail server, which I have never bothered doing.

Weird! You should be redirected to Sitepoint.
Try updating the code I posted last night, with the code I posted above and then see what happens.

I'm not too sure about this.
Normally you redirect your users to a "success" page on successful submission.
The reason for this is that if you bring them back to the same page, they can resubmit the form by reloading the page.
This would mean that someone could keep sending you mails, by pressing F5 over and over.
Saying that though, it must be possible.

Again. This is bizarre. It works fine for me.

No probs. In the above code, change this:

if (empty($mobile)){
  $error .= "You didn't enter a mobile number <br />";
} elseif (!eregi("^[0-9()+\\s-]+$", $mobile)){
  $error .= "The mobile number can only contain digits, spaces, brackets, plus or minus <br />";  
}

to this:

if (!empty($mobile) && !eregi("^[0-9()+\\s-]+$", $mobile)){
  $error .= "The mobile number can only contain digits, spaces, brackets, plus or minus <br />";  
}

As StarLion mentioned, $_POST always exists and you don't need to test for it.
That means you could write:

<?php
$robotest = $_POST['robotest'];
if($robotest)
  exit("die robot.");
else{
  echo '<div class="msg success">You are human and your message was sent!</div>';
}
?>

What I would suggest you do from here, is have a play around with the code and try to understand what is going on.
Try updating the code I provided, then post back here if there is anything that still isn't working.

Hope this helps.

#15

Hi,
Yes the code works well.

I see what you mean about redirecting users after submitting a contact form. Just created a quick success page with a message and a link to return back.

My idea is to achieve something along the lines on my attached image. Replacing the contact form DIV with a new one displaying a success message. Would this be acceptable?

Test emails still kind of work. I get name, email and message. No numbers. Maybe a Mac thing or MAMP settings? Though I can't see why.

Continuing to have a play around and get a grasp of whats going on. I have now about 15 versions of the same form.

Well its all good practice. My rowing club needs a new website so after I've hit the books and got a bit more experience I'll give that site a redesign too. Web developing is quite addictive and before I know it I've spent hours inside a time vaccum and its 3.00am in the morning!

#16

Good to hear things are progressing well.

Let's tackle the test email situation first and make sure that all of the values get through.

In the PHP code I provided this morning, can you change this:

$mailcontent = "Name: ". $name. "\
".
               "Email: ". $email. "\
\
".
               $message;

to this:

$mailcontent = "Name: ". $name. "\
".
               "Email: ". $email. "\
".
               "Landline: ". $landline. "\
".
               "Mobile: ". $mobile. "\
\
".
               $message;

Does that help any?

#17

Yes spot on! All the values get through. The only quirk is that how the test email displays. I typed "I am hungry. What's for dinner?" and got am hungry. What's for dinner?. It doesn't like apostrophes! Never mind though its only a minor detail.

Finally the success page. I've attached an image of how the page should look. The contact form div is redirected to a new div which displays a success message and send another email option.

To get a rough idea of how it will look I've just duplicated and renamed the page, replacing the contact form. So on submit you are redirected to a the new page. However I think just swapping the DIVs would be neater than linking in a whole new page

I definitely under estimated (as lots of people do) the complexity of developing a site. Most non techies seem to think its all drag and drop. I actually showed someone the markup and scripts and they were amazed at the complexity. Coming from a print/graphic background and fairly savvy on a mac I thought it'd be easy to pick up... my opinion has now changed!

#18

I never new how to do honeypot really either. So I just worked one up. Might help http://www.visibilityinherit.com/code/simple-php-honeypot.php

#19

Evening,

I've been doing some research and it seems that if the form does a HTTP redirect on itself, then the last "action" the browser remembers is a simple GET, so the form cannot be resubmitted upon refresh.

I've worked this into a code example for you.
As before you will have to alter your email address.
Also you will have to alter this line accordingly:

header("location: your-contact-form-address.php?success=1");

It should read something like

header("location: http://localhost/projects/contact.php?success=1");

Other than that, have a play around with it and see if it works for you.
The error messages etc, will need styling.

BTW: I am using

<?php echo htmlspecialchars($name, ENT_QUOTES); ?>

to repopulate the form with user input in the case of failed validation.
Printing user input back to the screen is always a security risk, so once we get this working, it is probably a good idea to start a new thread to find out if this is sufficient protection (or, if anyone is listening and knows the answer, please feel free to chime in).

<?php
    $name = '';
    $email =  '';
    $landline =  '';
    $mobile =  '';
    $message =  '';
     
  if ($_POST['s'] == 's'){
    $name = filter_var($_POST['name'],FILTER_SANITIZE_STRING);
    $email = filter_var($_POST['email'],FILTER_SANITIZE_STRING, FILTER_VALIDATE_EMAIL);
    $landline = filter_var($_POST['landline'], FILTER_SANITIZE_STRING);
    $mobile = filter_var($_POST['mobile'], FILTER_SANITIZE_STRING);
    $message = filter_var($_POST['message'],FILTER_SANITIZE_STRING);
    $robotest = $_POST['robotest']; 
      
    if($robotest){
      exit("Sorry, we think you're a bot!");
    }
    
    if (empty($name)){
      $error .= "You didn't enter a name <br />";
    }
    
    if (empty($email)){
      $error .= "You didn't enter an email address <br />";
    } elseif (!eregi("^[_a-z0-9-]+(\\.[_a-z0-9-]+)*@[a-z0-9-]+(\\.[a-z0-9-]+)*(\\.[a-z]{2,})\\.?$", $email)){
      $error .= "The email address appears to be invalid <br />";  
    }
    
    if (empty($landline)){
      $error .= "You didn't enter a landline number <br />";
    } elseif (!eregi("^[0-9()+\\s-]+$", $landline)){
      $error .= "The landline number can only contain digits, spaces, brackets, plus or minus <br />";  
    }
    
    // Optional Field
    if (!empty($mobile) && !eregi("^[0-9()+\\s-]+$", $mobile)){
      $error .= "The mobile number can only contain digits, spaces, brackets, plus or minus <br />";  
    }  
    
    if (empty($message)){
      $error .= "You didn't enter a message <br />";
    }
    
    if (empty($error)) {
      $toaddress = "your email address here";
      $fromaddress = "From:". $email;
      
      $mailcontent = "Name: ". $name. "\
".
                     "Email: ". $email. "\
".
                     "Landline: ". $landline. "\
".
                     "Mobile: ". $mobile. "\
\
".
                     $message;  
                                    
      mail($toaddress, "Website Contact Form", $mailcontent, $fromaddress);
      header("location: your-contact-form-address.php?success=1");
    } else {
      echo $error;
    }
  }
  
  if ($_GET['success']){
    echo("Message sent successfully");
  }
?>

<!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>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title>Pete's Contact Form with jQuery Validation</title>
    <script type="text/javascript" src="js/messages.js"></script>
    <style type="text/css">
      * {font-family: Arial, Helvetica, sans-serif;}
      body { background-color: #999;}
      .form label { font-size: 90%;} 
      .required_notification { font-size: 80%;} 
      
      /*CONTACT FORM - LEFT DIV*/
      #input_wrapper { width: 500px;
      padding: 10px 20px 20px 20px; 
      background: #555;
      background: -moz-linear-gradient(top, #444 0%, #666 50%); /* firefox */
      background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #444), color-stop(50%, #666)); /* webkit */
      border-radius: 3px;
      -moz-border-radius: 3px;
      -webkit-border-radius: 3px;
      -webkit-box-shadow: 0px 2px 2px #333333;
      box-shadow: 0px 2px 2px #333333;}
      
      /*Padding/margins/borders/outlines settings*/
      input, textarea {
      margin: 0;
      padding: 0;
      border: 0;
      outline: none;}
      
      /*Border Bottom*/    
      .form li:first-child, .contact_form li:last-child {
      border-bottom:1px solid #CCC;}
      /*Border Bottom*/  
      
      /*Padding/margins/borders/outlines*/
      
      /*No glowing edges to inputs!!!*/
      *:focus {outline: none;}
      /*No glowing edges to inputs!!!*/
      
      /*Header*/  
      .form h3 {
      margin:0px;
      display: inline;}
      
      .required_notification {
      color: #F06; /*#27AECF*/
      margin:5px 0 0 0; 
      display:inline;
      float:right;}
      /*Header*/  
      
      /*Contact form labels*/
      .form ul {
      width:500px;
      list-style-type:none;
      list-style-position:outside;
      margin:0px;
      padding:0px;}
      
      .form li{
      color:#FFF;
      padding:10px; 
      border-bottom:1px solid #999;
      position:relative;}
      
      .form label {
      width:80px;
      margin-top: 2px;
      display:inline-block;
      float:left;
      padding:3px;}
      
      #msg {display:none; 
      font-size:75%;
      position:absolute; 
      z-index:200; 
      background: url(images/msg_arrow.gif) left center no-repeat; 
      padding-left:7px;}
      
      #msgcontent {display:block; 
      background: #D6D6D6; 
      border:2px solid #F06; 
      border-left:none; 
      padding:5px; 
      min-width:192px; 
      max-width:192px;}
      
      /*Contact form labels*/
      
      /*Contact form inputs*/
      .form input:focus, .form textarea:focus { background-color: #EBEBEB;}
      
      /*Contact form text fields*/
      .form input { 
      font-family:Arial, Helvetica, sans-serif;
      font-size: 80%;
      background-color: #D6D6D6;
      /*border:1px solid #aaa;*/ 
      height:20px; 
      width:180px; 
      margin: 0px;
      padding:2px 5px;
      border-radius: 2px;
      -moz-border-radius: 2px;
      -webkit-border-radius: 2px;}
      /*Contact form text fields*/
      
      /*Contact textarea*/
      .form textarea { font-family:Arial, Helvetica, sans-serif; 
      font-size: 80%;
      width: 240px;
      height: 100px;
      padding: 5px 5px;
      background-color: #D6D6D6;/*padding-right:30px;*/
      /*border:1px solid #aaa;*/
      border-radius: 2px;
      -moz-border-radius: 2px;
      -webkit-border-radius: 2px;}
      /*Contact textarea*/  
      
      /*Contact form inputs*/
      
      /*input/textarea placeholder text*/
      input::-webkit-input-placeholder { color: #777;}
      input:-moz-placeholder { color: #777;}
      ::-webkit-input-placeholder { color: #777;}
      :-moz-placeholder { color: #777;}
      /*input/textarea placeholder text*/
      
      /*sprite email button*/  
      input.submit { width: 148px; 
      height: 40px;
      margin-left: 190px;
      background-position: 0px 0px;
      background-color: transparent; /* or #666*/
      background-image: url(images/email_sprite.png);
      /*background:transparent url(images/email_sprite.png);*/
      text-indent: -9999px;
      display: inline-block; 
      border:none;
      outline:none;} 
      
      input.submit:hover { background-position: 0px -40px;}
      input.submit:active { background-position: 0px -80px;}
      /*sprite email button*/    
      
      .robotic { display:none; }
      
      /*CONTACT FORM - LEFT DIV*/  
    </style>
  </head>
  
  <body>
    <div id="input_wrapper">
      <form name="form" id="form" class="form" action="" onsubmit="return validate(this)" method="post">
        <ul>
          <li>
            <h3>Contact Us</h3>
            <span class="required_notification">* Denotes Required Field</span>
          </li>
          <li>
            <label for="name">Name:</label>
            <input type="text" name="name" id="name" placeholder="Enter your full name *" value="<?php echo htmlspecialchars($name, ENT_QUOTES); ?>" />
          </li>
          <li>
            <label for="email">Email:</label>
            <input type="text" name="email" id="email" placeholder="Enter your email address *" value="<?php echo htmlspecialchars($email, ENT_QUOTES); ?>"/>
          </li>
          <li>
            <label for="telephone">Phone:</label>
            <input type="text" name="landline" id="landline" placeholder="Enter your landline number *" value="<?php echo htmlspecialchars($landline, ENT_QUOTES); ?>"/>
          </li>  
          <li>  
            <label for="mobile">Mobile:</label>
            <input type="text" name="mobile" id="mobile" placeholder="Enter your mobile number *" value="<?php echo htmlspecialchars($mobile, ENT_QUOTES); ?>"/>
          </li> 
          <li>  
            <label for="message">Message:</label>
            <textarea id="message" name="message" placeholder="Enter your message here...*"><?php echo htmlspecialchars($message, ENT_QUOTES); ?></textarea>     
          </li>
          
          <!-- The following field is for robots only, invisible to humans: -->
          <li class="robotic">
            <label for="robotest">If you're human leave this blank:</label>
            <input type="text" id="robotest" name="robotest" class="robotest" />
          </li>  
                  
          <li>
            <input type="hidden" value="s" name="s" />
            <input type="submit" value="submit" class="submit"/>
          </li>
        </ul>
      </form>
    </div>
    
    <script>
      // form validation function //
      function validate(form) {
        var name = form.name.value;
        var email = form.email.value;
        var message = form.message.value;
        var nameRegex = /^[a-zA-Z]+(([\\'\\,\\.\\- ][a-zA-Z ])?[a-zA-Z]*)*$/;
        var emailRegex = /^[\\w-\\.]+@([\\w-]+\\.)+[\\w-]{2,4}$/;
        var messageRegex = new RegExp(/<\\/?\\w+((\\s+\\w+(\\s*=\\s*(?:".*?"|'.*?'|[^'">\\s]+))?)+\\s*|\\s*)\\/?>/gim);
        if(name == "") {
          inlineMsg('name','Please enter your name!',2);
          return false;
        }
        if(!name.match(nameRegex)) {
          inlineMsg('name','Please enter an invalid name!',2);
          return false;
        }
        if(email == "") {
          inlineMsg('email','<strong>Error!</strong> Please enter your email!',2);
          return false;
        }
        if(!email.match(emailRegex)) {
          inlineMsg('email','<strong>Error!</strong> This email is invalid!',2);
          return false;
        }
        if(message == "") {
          inlineMsg('message','Please enter your message!');
          return false;
        }
        if(message.match(messageRegex)) {
          inlineMsg('message','This message is invalid!');
          return false;
        }
        return true;
      }
      
      // START OF MESSAGE SCRIPT //
      
      var MSGTIMER = 20;
      var MSGSPEED = 5;
      var MSGOFFSET = 3;
      var MSGHIDE = 3;
      
      // build out the divs, set attributes and call the fade function //
      function inlineMsg(target,string,autohide) {
        var msg;
        var msgcontent;
        if(!document.getElementById('msg')) {
          msg = document.createElement('div');
          msg.id = 'msg';
          msgcontent = document.createElement('div');
          msgcontent.id = 'msgcontent';
          document.body.appendChild(msg);
          msg.appendChild(msgcontent);
          msg.style.filter = 'alpha(opacity=0)';
          msg.style.opacity = 0;
          msg.alpha = 0;
        } else {
          msg = document.getElementById('msg');
          msgcontent = document.getElementById('msgcontent');
        }
        msgcontent.innerHTML = string;
        msg.style.display = 'block';
        var msgheight = msg.offsetHeight;
        var targetdiv = document.getElementById(target);
        targetdiv.focus();
        var targetheight = targetdiv.offsetHeight;
        var targetwidth = targetdiv.offsetWidth;
        var topposition = topPosition(targetdiv) - ((msgheight - targetheight) / 2);
        var leftposition = leftPosition(targetdiv) + targetwidth + MSGOFFSET;
        msg.style.top = topposition + 'px';
        msg.style.left = leftposition + 'px';
        clearInterval(msg.timer);
        msg.timer = setInterval("fadeMsg(1)", MSGTIMER);
        if(!autohide) {
          autohide = MSGHIDE;  
        }
        window.setTimeout("hideMsg()", (autohide * 1000));
      }
      
      // hide the form alert //
      function hideMsg(msg) {
        var msg = document.getElementById('msg');
        if(!msg.timer) {
          msg.timer = setInterval("fadeMsg(0)", MSGTIMER);
        }
      }
      
      // face the message box //
      function fadeMsg(flag) {
        if(flag == null) {
          flag = 1;
        }
        var msg = document.getElementById('msg');
        var value;
        if(flag == 1) {
          value = msg.alpha + MSGSPEED;
        } else {
          value = msg.alpha - MSGSPEED;
        }
        msg.alpha = value;
        msg.style.opacity = (value / 100);
        msg.style.filter = 'alpha(opacity=' + value + ')';
        if(value >= 99) {
          clearInterval(msg.timer);
          msg.timer = null;
        } else if(value <= 1) {
          msg.style.display = "none";
          clearInterval(msg.timer);
        }
      }
      
      // calculate the position of the element in relation to the left of the browser //
      function leftPosition(target) {
        var left = 0;
        if(target.offsetParent) {
          while(1) {
            left += target.offsetLeft;
            if(!target.offsetParent) {
              break;
            }
            target = target.offsetParent;
          }
        } else if(target.x) {
          left += target.x;
        }
        return left;
      }
      
      // calculate the position of the element in relation to the top of the browser window //
      function topPosition(target) {
        var top = 0;
        if(target.offsetParent) {
          while(1) {
            top += target.offsetTop;
            if(!target.offsetParent) {
              break;
            }
            target = target.offsetParent;
          }
        } else if(target.y) {
          top += target.y;
        }
        return top;
      }
      
      // preload the arrow //
      if(document.images) {
        arrow = new Image(7,80); 
        arrow.src = "images/msg_arrow.gif"; 
      }
    </script>
  </body>
</html>

#20

Vielen dank, muchas gracias, merci beaucoup, grazie mille, tack sa mycket! I use to pick up languages fairly well when I lived abroad... lets hope its the same with computer languages.

I swapped this:

header("location: your-contact-form-address.php?success=1");

for this:

header("location: http://localhost/projects/contact.php?success=1");

On submitting the new form it appears to redirect on itself which is http://localhost:8888

However test emails fail to send, which is odd as the previous form still works.

As I already have styled Javascript validation messages are you referring to your code:

if ($_GET['success']){
         echo("Message sent successfully");

If I have to style the success message would my very first attempt at PHP work work?:

if ($_GET['success']){
           echo '<div class="msg success">'.$success.'</div>';
	}
?>

Sorry if I sound dum! Although I was good a maths so can't be that dense... maybe my mental capacity has slowed down as I've grown older.