<?php

// Simple Contact Us form written in PHP and incorporating the
// Spamerator.com CAPTCHA service

// Replace these with your preference
$adminemail="admin@yoursite.com";
$subject="You Received a Contact Request!";

// Firstly, we are going to use the php session method for maintaining a
// unique user key for the spamerator.com web service. We will only take a
// snippet of it for security reasons.

session_start();
$SESSIONID=substr(session_id(),0,10);

?>

<html>
<head>
<title>Sample Contact Us Form</title>
</head>
<body>

<?php


// Detect whether we have data submission, otherwise send them the contact
// us form.

if($_POST["submit"]) {
  // Let's clean the incoming data for alphanumeric characters only
  $c=preg_replace("/[^a-zA-Z0-9]/", "",$_POST["checkcaptcha"]);
  
  if(file_get_contents("http://www.spamerator.com/handler.php?u=$SESSIONID&c=$c")=="1") {
    echo "Correct Captcha!";

    // Let's clean all the incoming contact data
    $fromemail=preg_replace("/[^@a-zA-Z0-9\.]/", "", $_POST["fromemail"]);
    $message=preg_replace("/[^@\ a-zA-Z0-9\.]/", "", $_POST["message"]);

    // Let's send the message to the admin
    mail($adminemail,$subject,"Here is what your user (".$fromemail.") had to say:\r\n".$message,"From: ".$adminemail);
    echo "<br /><br />Your message was sent.";

  } else {
    echo "Incorrect Captcha.  Try again.";
  }
} else {
  // Output an HTML form to accept a contact request

  echo "<h1>Contact Us!</h1>";
  echo "<h2>Use this form to send a message to the admin.</h2>";
  echo "<form method=\"post\" action=\"".$_SERVER['PHP_SELF']."\">";
  echo "Your Email: <input type=\"text\" size=\"40\" name=\"fromemail\"><br />";
  echo "Your Comment: <br /> <textarea cols=\"40\" rows=\"4\" name=\"message\"></textarea><br />";
  echo "<img /src=\"http://www.spamerator.com/handler.php?u=$SESSIONID\" /><br />";
  echo "Type the number you see in the above image: <input /type=\"text\" size=\"10\" name=\"checkcaptcha\" /><br />";
  echo "<input type=\"submit\" name=\"submit\" value=\"submit\" /></form>";
}

?>

</body>
</html>