Spam entries into a Form help

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Addos
Forum Contributor
Posts: 305
Joined: Mon Jan 17, 2005 4:13 pm

Spam entries into a Form help

Post by Addos »

I wonder if anybody can help me stop spam being entered into various forms I have on a few sites?

I have a submit form for example here http://www.conor-cummins.com/guestbook_sign.php which has lots of validation in it but still I keep getting entries being made and the latest entry filled all the values in MySQL database with ‘null’ for example the top one here http://www.conor-cummins.com/guestbook.php

I don’t get more than one or two a day but it’s very annoying and I would love to know if I can get around this. The code of the Submit Form is below and if anybody can help me or advise me I’d be most grateful.

Many thanks

Brian

Code: Select all

<?php require_once(*************); ?>
<?php
// Test whether the POST array has been set and makes certain 
// variables are initialzed with no content.
$pattern = '/^\w[-.\w]*@([-a-z0-9]+\.)+[a-z]{2,4}$/i';
if ($_POST && array_key_exists('sendCom',$_POST)) {
  $nomessage='';
  $nospam='';
  $error=array();
  $error_email=array();
  $message='';
  $GuestEmail= $_POST['GuestEmail'];
  $trimedGuestDetails = $_POST['GuestDetails'];
  $trimedGuestName = $_POST['GuestName'];
// check to see if space bar has been used and if so send an error
if (!trim($trimedGuestDetails) && !empty($_POST['GuestDetails'])) {
    $nomessage = 'Message Required!';
	}
// Trim out white space and srtip out unwanted HTML
if (isset($_POST['GuestDetails']) && !empty($_POST['GuestDetails'])) {
$trimedGuestDetails=trim(strip_tags($_POST['GuestDetails']));
}else{
   $nomessage = 'Message Required';
  }
// check to see if space bar has been used and if so send an error
if (!trim($trimedGuestName) && !empty($_POST['GuestName'])) {
    $error['GuestName'] = 'Name Required!';
	}
	  
if (isset($_POST['GuestName']) && !empty($_POST['GuestName'])) {
$trimedGuestName=trim(strip_tags($_POST['GuestName']));
}else {
  $error['GuestName'] = 'Name Required';
  }
// Stop Robots spaming form
// Conditional check for empty fields
 $spammed = trim(strtolower($_POST['StopSpam']));
if ($spammed ==='wednesday' && !empty($_POST['StopSpam'])) {
}else{
   $nospam = 'Error: You must answer the question';
 }   
   // Removes HTTP:// or http:// and strips white space
	 $url = trim($_POST['GuestWebsite']);
	 if (strpos(strtolower($url), 'http://') ===0) {
	 $url = substr($url, 7);
	}
 if (empty($_POST['GuestEmail'])) {// validation of email if inserted otherwise ignore
	 } else {
	 if (!preg_match($pattern,$GuestEmail)) $error_email['invalid'] = 'ERROR! Your email address seems to be invalid. <br> It should be similar to the following: info@me.com';
     }
	 }
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") 
{
  $theValue = (!get_magic_quotes_gpc()) ? addslashes($theValue) : $theValue;

  switch ($theType) {
    case "text":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;    
    case "long":
    case "int":
      $theValue = ($theValue != "") ? intval($theValue) : "NULL";
      break;
    case "double":
      $theValue = ($theValue != "") ? "'" . doubleval($theValue) . "'" : "NULL";
      break;
    case "date":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;
    case "defined":
      $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
      break;
  }
  return $theValue;
}

$editFormAction = $_SERVER['PHP_SELF'];
if (isset($_SERVER['QUERY_STRING'])) {
  $editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']);
}

if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "form1")) {
if (!$nomessage && !$error)  {
if (!$nomessage && !$error_email)
if (!$nomessage && !$nospam)    {
// If no errors, send email and redirect to acknowledgment page
 // User has entered an email address
  						
		mail($to,$subject,$message,$headers);							
		  $insertSQL = sprintf("INSERT INTO tblguestbook (GuestName, GuestLocation, GuestDetails, GuestWebsite, GuestEmail, ip, GuestDate) VALUES (%s, %s, %s, %s, %s, '".$_SERVER['REMOTE_ADDR']."', CURDATE())",
                       GetSQLValueString("$trimedGuestName", "text"),
                       GetSQLValueString($_POST['GuestLocation'], "text"),
                       GetSQLValueString("$trimedGuestDetails", "text"),
                       GetSQLValueString("$url", "text"),
                       GetSQLValueString($_POST['GuestEmail'], "text"));
					 


  mysql_select_db($****, $****);
  $Result1 = mysql_query($insertSQL, $cummins_database) or die(mysql_error());

  $insertGoTo = "guestbook.php";
  if (isset($_SERVER['QUERY_STRING'])) {
    $insertGoTo .= (strpos($insertGoTo, '?')) ? "&" : "?";
    $insertGoTo .= $_SERVER['QUERY_STRING'];
  }
  header(sprintf("Location: %s", $insertGoTo));
}}}?>


<table border="0" align="center" cellpadding="0" cellspacing="0" class="tbl_outer" id="tbl_outer">
          <tr><td class="mainContent">

</td>
</tr>
 <tr>
   <td id="error"><?php 
	  if (isset($error_email)) {	  
		foreach ($error_email as $key => $value) {
		  echo $value.'<br />';
		  }
		  }
		?>
     <p>&nbsp;</p></td>
 </tr>
 <tr>
    <td>      <form method="post" name="form1" action="<?php echo $editFormAction; ?>">
        <table>
          <tr valign="baseline">
            <td align="right" nowrap class="error" id="error">* Name: <br>
			<?php 
	  if (isset($error)) { // Display error messages. Otherwise skip table row.
	   // Loop through error messages and display
		foreach ($error as $key => $value) {
		  echo $value.'<br />';
		  }
		  }
		?></td>	
            <td><input type="text" name="GuestName" id="GuestName" size="32" value="<?php if (isset($_POST['GuestName'])) echo $_POST['GuestName'];?>" ></td>
          </tr>
          <tr valign="baseline">
            <td nowrap align="right">Location:</td>
            <td><input type="text" name="GuestLocation" value="" size="32"></td>
          </tr>
           <tr valign="baseline">
            <td align="right" valign="top" nowrap class="error" id="error">* Message: <br>
			<?php if (isset($nomessage) && !empty($nomessage)) {
		  echo $nomessage; } else { 		 
		  } ?></td>
            <td><textarea name="GuestDetails" cols="40" rows="5" id="GuestDetails"><?php if (isset($_POST['GuestDetails'])) echo $_POST['GuestDetails'];?></textarea>
            </td>
          </tr>
          <tr valign="baseline">
           <td nowrap align="right">Website Address:</td>
		  <td><input type="text" name="GuestWebsite" value="<?php if (isset($_POST['GuestWebsite'])) echo $_POST['GuestWebsite'];?>" id ="GuestWebsite" size="32"></td>
          </tr>
          <tr valign="baseline">
            <td nowrap align="right">Email Address:
			</td>
			
            <td><input type="text" name="GuestEmail" id="GuestEmail" value="<?php if (isset($_POST['GuestEmail'])) echo $_POST['GuestEmail'];?>" size="32"></td>
          </tr>
		  <tr valign="baseline">
            <td nowrap align="right">Help Stop Spam by </td>
            <td>answering the following question.</td>
		            </tr>
		    <tr valign="baseline" id="error">
            <td nowrap align="right">
                * What day comes after Tuesday?: <br>
			        <?php if (isset($nospam) && !empty($nospam)) {
			 echo $nospam; } else { 		 
			 } ?>
			   
              </td>
            <td><input type="text" name="StopSpam" id="StopSpam" value="<?php if (isset($_POST['StopSpam'])) echo $_POST['StopSpam'];?>" size="32"></td>
          </tr>
          <tr valign="baseline">
            <td nowrap align="right">* Required Field </td>
            <td><input name="sendCom" type="submit" id="sendCom" value="Post Message" />
	   <input name="Reset" type="reset" value="Reset"></td>
          </tr>
        </table>
		<input type="hidden" name="MM_insert" value="form1">
      </form>
   </td>
  </tr>
</table>
Charles256
DevNet Resident
Posts: 1375
Joined: Fri Sep 16, 2005 9:06 pm

Post by Charles256 »

perhaps generate some random text with PHP that the user must enter? most robots can't read that:-Dand also add a check to see if a field has "null" in it, :-D That'll stop your specific example.heh
Addos
Forum Contributor
Posts: 305
Joined: Mon Jan 17, 2005 4:13 pm

Post by Addos »

Hi,
Just wondering how I can check for a ‘null’ value? Now I’m still new to most of this but I thought that for example:

Code: Select all

if (isset($_POST['GuestName']) && !empty($_POST['GuestName'])) { 
$trimedGuestName=trim(strip_tags($_POST['GuestName'])); 
}else { 
  $error['GuestName'] = 'Name Required'; 
  }
tests for a null value. MYSQL database automatically inserts a ‘Null’ value into the table in order to avoid an error. Sorry if I’ve missed the point but any more help would be great.
Thanks a mil
Brian
Charles256
DevNet Resident
Posts: 1375
Joined: Fri Sep 16, 2005 9:06 pm

Post by Charles256 »

if it's inserting a null value because the field is empty check to see if the entry is empty using the empty() function:-D
User avatar
Ambush Commander
DevNet Master
Posts: 3698
Joined: Mon Oct 25, 2004 9:29 pm
Location: New Jersey, US

Post by Ambush Commander »

Keyword: Captcha
Addos
Forum Contributor
Posts: 305
Joined: Mon Jan 17, 2005 4:13 pm

Post by Addos »

Forgive my persistence but I’m quite new to all of this and don’t seem to be able to follow fully what you mean. Should I be trying something like the following?

Code: Select all

if (empty($_POST['GuestDetails'])) {
   echo 'Remove echo once this conditional statement is sorted’ ;
Thanks too Ambush Commander

But I don’t know what you mean when you say Keyword: Captcha Can you explain?

Thanks
B
User avatar
shiznatix
DevNet Master
Posts: 2745
Joined: Tue Dec 28, 2004 5:57 pm
Location: Tallinn, Estonia
Contact:

Post by shiznatix »

User avatar
Maugrim_The_Reaper
DevNet Master
Posts: 2704
Joined: Tue Nov 02, 2004 5:43 am
Location: Ireland

Post by Maugrim_The_Reaper »

If its also being filled from a copied form (i.e. not the form you present) you can use a form_id hidden field to stored a random string which is sent back to the server, agrees to the database stored copy, and can only be used once - something good for cross site request forgeries...

Bit similar to C/R - see my tutorial - only no password hashing, just a simple hash unique to all forms requested and submitted.

If they are using you own form from your site - CAPTCHA may be the sure fire solution. Just keep in mind that you will not win any accolades from people with screen readers and sight problems - a big problem with CAPTCHA and why I will probably never use it.
Post Reply