Spam Honey Pot trap

Gern geschehen, ¡Con mucho gusto! De rien! Prego! and Ingen orsak! (in that order :))

Try changing it to:

header("location:" . $_SERVER['PHP_SELF'] . "?success=1");

Does that work?

As the form resubmits to itself, you need some way of determining if it is loading for the first time (i.e. a brand new visitor), or if it is loading after a submission (i.e. the visitor has filled out the form and pressed ‘send’).
If it is loading for the first time, you obviously want to display just the form and leave it at that.
However, if the form is loading after the user has pressed ‘send’, you then need to work out if a mail was sent, or if validation failed, so that you can display a confirmation message or an error message accordingly.
These are the messages I’m talking about.

Let’s see if we can get the form working properly, first, then you should hopefully see what I mean.
If it works as it should and sends a mail, you will see a confirmation message printed at the top of the page.

Regarding the validation messages, you will need to turn off JavaScript to see these.
Which browser are you using?

No, not at all. We’ve all got to learn somewhere. I think it’s great that you’re having a go at this in the first place!

Nothing like learning by jumping in at the deep end.

It works. Easy fix. I thought I better check the HTML and discovered myScript.php was missing from the action tag of the form.

Can the contact form div be swapped for new div with the success message in?

A extremely rough idea of what I’d like to see:

I’m actually enjoying a new challenge and intend to keep going!

Hi there,

I’m afraid that the action tag was intentionally left blank.
This way the form could submit to itself.
:frowning:

We will arrive at the point that you can style the “success” page as per your attachment, but, as you said yourself, it is quite a complicated process with several hidden gotchas, so it’s best to make sure that everything is working, before heading on to the next step.

So, I’ve amended the code.
Please copy this code into a PHP file (not HTML) on your computer and save it somewhere in the htdocs folder which is accessed by your MAMP server.

Then change the email address in the following line, to your email address:

$toaddress = "your email address here";

Don’t change anything else in the code.

Then, don’t open the file directly in your browser, rather navigate to the file using the correct url.
For me (on Windows in xampp) this is http://localhost/projects/contact.php

For you it will be something with localhost:8888 presumably.
Important: it shouldn’t be anything like “file:///Volumes/Pete’s%20Backup/Documents/Sites/www.stuartlighting.co.uk/contact13.html”

If you then fill out the form and submit it, the form should redirect to itself (i.e. effectively re-render itself) and you should see a new message at the very top of the page which reads “Message sent successfully”.
The url (in the address bar) should still be the same, but will have “?success=1” appended to it.

Is this the case for you?

Sorry if I’m telling you stuff you already know, but there are so many things that could go wrong along the way, I just want to make sure we’re both on the same page.

Now the code:

<?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:" . $_SERVER['PHP_SELF'] . "?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>

So to sum it all up.

Before I had placed the myScript.php in the action tag. The form sent the message and was I redirected to a white page which read “Message sent successfully” and http://localhost:8888/myScript.php?success=1 appeared in the browser URL.

Ok, so the action tag is now blank again. I already added my email to the $toaddress.

Rather than preview the browser in Dreamweaver I navigated Safari to location localhost:8888 . The contact form does submit to itself which resets the form but no success message and the URL remains localhost:8888. Alternatively in MAMP I can press the home button which takes me to localhost:8888. Same thing happens

The directory for the contact form: localhost/contactform3/index.php
The directory for the php script: localhost/contactform3/myScript.php

With regard to MAMP I’ve changed the default folder from htdocs to my localhost folder.

The htdocs folder is located in the MAMP folder in Applications.

Will this make any difference?

Hi there,

Before any of this can work, we need to establish a few things about your setup:

  • That you can view PHP pages with your browser that are served up via Apache (the ‘A’ in MAMP)
  • That PHP’s mail() function works as expected
  • That PHP’s header() function works as expected

Sorry if this feels like we’re taking steps backwards, but it is important to do this now, as even if you manage to patch together something that works for you locally, it’ll most likely break as soon as you deploy it to a remote server.

So, let’s start over.

From the MAMP documentation:

By default, PHP and HTML Pages should be stored inside the MAMP “htdocs” folder which is located in the MAMP Application directory /Applications/MAMP. This folder is called “Document Root”.

Please do the following:

Change the path for the Document Root back to “/Applications/MAMP/htdocs”.
You can do this in the MAMP application’s Preferences Panel.

Copy the following code into a file and save it as “test.php” in the aforementioned “htdocs” folder.

<?php
  echo "Hello, world!<br>";
  echo "Current server time is: " . date("H:i:s");
?>

Navigate to http://localhost:8888/test.php

What do you see?

Hi, Its Friday night! Beers in soon!

I did try shifting the contact form over to that location but had no luck. Will try and try again.

If I save test.php to “/Applications/MAMP/htdocs” then I get:
Forbidden
You don’t have permission to access / on this server.

If I rename the test.php index.php I get:
Hello, world!
Current server time is: 20:20:34

Ok, so you can access the file at http://localhost:8888/index.php
and you see something like:

Hello, world!
Current server time is: 20:20:34

Is that correct?

Man, I would love to be in an English pub right now! (I’m from England originally).
Actually, I would love to be in any pub right now.
:slight_smile:

Just to confirm I can see:

Hello, world!
Current server time is: 20:20:34

Provided the php file is named index.php

Sorry, we’re getting our wires crossed a little.
I also want to know the url in the address bar.
Is it http://localhost:8888/index.php ?

its http://localhost:8888 not http://localhost:8888/index.php.

Ah, ok.
If you go to http://localhost:8888, then you will hit the site’s root directory and Apache will look for either “index.html” or “index.php” and load whichever one of those it finds.
So, two more questions.

If you type http://localhost:8888/index.php into your browser, do you see the same file?

Then if you rename the file to “test.php”, can you view it by typing http://localhost:8888/test.php into your browser?

Edit: The reason you were getting the error

Forbidden 
You don't have permission to access / on this server.

was because you named the file “test.php”, but were (very probably) viewing http://localhost:8888/.
As there was no index file present, Apache then thought you were trying to access the contents of the folder, which seems to be forbidden on your machine.

Yes If rename it test.php and type http://localhost:8888/test.php I see the same file.

Cool and the gang!

So, next thing to establish.
What happens if you hard-code the mail details into the script:

<?php
  echo "Hello, world!<br>";
  echo "Current server time is: " . date("H:i:s");
	
  $toaddress = "your address here";
  $fromaddress = "From: bob@yahoo.com";
  $message = "Hello, there!";  
                                    
  mail($toaddress, "Website Contact Form", $message, $fromaddress);
?>

Let’s stay with test.php for the time being.

What happens when you update test.php with this code, then go to http://localhost:8888/test.php ?
(Obviously, you should enter your own address in the script).

You should still see the same output, but do you get a mail?

Yes that works.

No pub after all!

Dude, don’t let me stop you going to the pub!!!
I’m almost tempted to bow out here, so you get your beer time in :slight_smile:

So, last point to establish:

Amend the “test.php” code like this:

<?php
  $toaddress = "your address here";
  $fromaddress = "From: bob@yahoo.com";
  $message = "Hello, there!";  
                                    
  mail($toaddress, "Website Contact Form", $message, $fromaddress);
  header("Location: http://www.sitepoint.com");
?>

Navigate to http://localhost:8888/test.php.
Do you get a mail and get redirected to SitePoint?

I get a message but I don’t get redirected.

I watching a rugby match on TV and might go out for last orders. Christmas has left me a bit broke so its probably a good idea if I have a quieter evening.

Ok, there’s the problem!
The code I was posting, cannot work as it relies on the redirect working.
:frowning:

I’ll have a play around and post back in a bit.

I know that feeling.
I’m going to raid the fridge and have an non-alcoholic beer in sympathy.

I found one post from someone having the same issue.
They claim to have solved it by altering their output_buffering setting.

Could you do the following:

Paste this code into a file named “info.php”

<?php
  phpinfo();
?>

Save the file in your “htdocs” folder, then in your browser navigate to http://localhost:8888/info.php.

You’ll see a load of information.
Do an in-page search for “output_buffering”.
What value does it have next to it?

And the answer is:
output_buffering no value no value