www.webdeveloper.com
Results 1 to 5 of 5

Thread: PHP Contact Form, Rejecting Spam (Links) from being Submitted

  1. #1
    Join Date
    Oct 2008
    Posts
    17

    PHP Contact Form, Rejecting Spam (Links) from being Submitted

    Hi all.

    I'd greatly appreciate some help in modifying my script for a contact form. I thought it was good to start but now I'm realizing that it does ok for the non-human element but the human element is killing me lately. Either way, I'd like my next modification to be a catch for links being submitted in the comments section of the form. I've tried several (at least 5) ideas to get this running but have had minimal luck to say the least.

    Here's the page code:
    Code:
    <?php 
    if (array_key_exists('send', $_POST)) {
    	// mail processing script
    	$to = 'rothnd.webster@gmail.com';
    	$me = 'rothnd.webster@gmail.com';
    	$subject = 'Feedback From Website';
    	
    	// list expected fields
    	$expected = array('name', 'email', 'comments');
    	// set required fields
    	$required = array('name', 'email', 'comments');
    	
    	// set additional headers
    	$headers = 'From: Megan Roth<feedback@meganroth.com>';
    
    	// set the include
    	$process = 'includes/process.inc.php';
    	if (file_exists($process) && is_readable($process)) {
    		include($process);
    	}
    	else {
    		$mailSent = false;
    		mail($me, 'Server Problem', "$process cannot be read", $headers);
    	}
    }
    ?>
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
    <html>
    <head>
    	...
        <script type="text/javascript">
    	<!--
    	function MM_validateForm() { //v4.0
    	  if (document.getElementById){
    	    var i,p,q,nm,test,num,min,max,errors='',args=MM_validateForm.arguments;
        	for (i=0; i<(args.length-2); i+=3) { test=args[i+2]; val=document.getElementById(args[i]);
        	  if (val) { nm=val.name; if ((val=val.value)!="") {
        	    if (test.indexOf('isEmail')!=-1) { p=val.indexOf('@');
        	      if (p<1 || p==(val.length-1)) errors+='- '+nm+' must contain an e-mail address.\n';
        	    } else if (test!='R') { num = parseFloat(val);
        	      if (isNaN(val)) errors+='- '+nm+' must contain a number.\n';
            	  if (test.indexOf('inRange') != -1) { p=test.indexOf(':');
            	    min=test.substring(8,p); max=test.substring(p+1);
            	    if (num<min || max<num) errors+='- '+nm+' must contain a number between '+min+' and '+max+'.\n';
          	} } } else if (test.charAt(0) == 'R') errors += '- '+nm+' is required.\n'; }
        	} if (errors) alert('The following error(s) occurred:\n'+errors);
        	document.MM_returnValue = (errors == '');
    	} }
    	//-->
        </script>
    </head>
    
    <body>
    
    <div id="page-container">
    	
        <div id="header"></div>
    
      	<?php include("includes/navigation.inc.php"); ?>   
    
    	<div id="border">
      		<div id="content">
                                  
                    <?php 
    				if ($_POST && isset($missing) && !empty($missing)) {
    				?>
                    <p class="warning">Please complete the missing item(s) indicated.</p>
                    <?php
    				}
    				elseif ($_POST && !$mailSent) {
    				?>
                    <p class="warning">Sorry, there was a problem sending your message. Please try again later.</p>
                    <?php
    				}
    				elseif ($_POST && $mailSent) {
    				?>
                    <p class="success">Your message has been sent. Thank you for your comments!</p>
                    <?php } ?>
                    <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" name="contact" id="contact" onSubmit="MM_validateForm('name','','R','email','','RisEmail','comments','','R');return document.MM_returnValue">
                      <p>
                        <label for="name">Name: <?php
    					if (isset($missing) && in_array('name', $missing)) { ?>
                        <span class="warning">Please enter your name</span><?php } ?>
                        </label>
                        <input name="name" type="text" class="textInput" id="name" 
                        <?php if (isset($missing)) {
    						echo 'value="'.htmlentities($_POST['name'], ENT_QUOTES).'"';
    						} ?>
                        >
                      </p>
                      <p>
                        <label for="email">Email: <?php
    					if (isset($missing) && in_array('email', $missing)) { ?>
                        <span class="warning">Please enter your email address</span><?php } ?>
                        </label>
                        <input name="email" type="text" class="textInput" id="email"
                        <?php if (isset($missing)) {
    						echo 'value="'.htmlentities($_POST['email'], ENT_QUOTES).'"';
    						} ?>
                        >
                      </p>
                      <p>
                        <label for="comments">Comments:<?php
    					if (isset($missing) && in_array('comments', $missing)) { ?>
                        <span class="warning">Please enter your comments</span><?php } ?>
                        </label>
                        <textarea name="comments" id="comments" cols="45" rows="5"><?php 
    						if (isset($missing)) {
    							echo htmlentities($_POST['comments'], ENT_QUOTES);
    						} ?></textarea>
                      </p>
                      <p>
                      	<?php
                        	require_once('recaptchalib.php');
      						$publickey = "6Lf3NdQSAAAAAOAwgPGRybLnY175X6k9PJ1F2vHx"; // you got this from the signup page
     						echo recaptcha_get_html($publickey);
      					?>
                      </p>
                      <p>
                        <input type="submit" name="send" id="send" value="Send Comments">
    				  </p>
    				</form> 
    				<h1>Please take this time to send comments and your email address so we can stay in touch with you!</h1>
              </div>
        </div>                      
    
    </div>    
    
    </body>
    </html>
    And here is the processing script itself:
    Code:
    <?php
      require_once('recaptchalib.php');
      $privatekey = "6Lf3NdQSAAAAAL8eoJYsc5llALDqnEtF4bx5JwRz";
      $resp = recaptcha_check_answer ($privatekey,
                                    $_SERVER["REMOTE_ADDR"],
                                    $_POST["recaptcha_challenge_field"],
                                    $_POST["recaptcha_response_field"]);
    
      if (!$resp->is_valid) {
        // What happens when the CAPTCHA was entered incorrectly
        die ("The reCAPTCHA wasn't entered correctly. Go back and try it again." .
             "(reCAPTCHA said: " . $resp->error . ")");
      } else {
        if (isset($_SERVER['SCRIPT_NAME']) && strpos($_SERVER['SCRIPT_NAME'], 'inc.php')) exit;
    
    // remove escape characters from POST array
    if (get_magic_quotes_gpc()) {
      	function stripslashes_deep($value) {
        	$value = is_array($value) ? array_map('stripslashes_deep', $value) : stripslashes($value);
        	return $value;
        }
      $_POST = array_map('stripslashes_deep', $_POST);
    }
    
    	// create empty array for any missing fields
    	$missing = array();
    	
    	// assume that there is nothing suspect
    	$suspect = false;
    	// create a pattern to locate suspect phrases
    	$pattern = '/Content-Type:|Bcc:|CC:/i';
    	// function to check for suspect phrases
      	function isSuspect($val, $pattern, &$suspect) {
        // if the variable is an array, loop through each element
    	// and pass it recursively back to the same function
    	if (is_array($val)) {
          foreach ($val as $item) {
    	    isSuspect($item, $pattern, $suspect);
    	    }
    	}
        else {
          // if one of the suspect phrases is found, set Boolean to true
    	  if (preg_match($pattern, $val)) {
            $suspect = true;
    	    }
    	  }
        }
    	
    	// check the $_POST array and any subarrays for suspect content
    	isSuspect($_POST, $pattern, $suspect);
    	
    	if ($suspect ) {
    		$mailSent = false;
    		unset($missing);
    	}
    	else {
    	// process the $_POST variables
    		foreach ($_POST as $key => $value) {
    			// assign to temporary variable and strip whitespace if not an array
    			$temp = is_array($value) ? $value : trim($value);
    			// if empty and required, add to $missing array
    			if (empty($temp) && in_array($key, $required)) {
    				array_push($missing, $key);
    			}
    			// otherwise, assign to a variable of the same name as $key
    			elseif (in_array($key, $expected)) {
    				${$key} = $temp;
    			}
    		}
    	}
    	
    	// validate the email address
    	if (!empty($email)) {
    		// regex to identify illegal characters in email address
    		$checkEmail = '/^[^@]+@[^\s\r\n\'";,@%]+$/';
    		// reject the email address if it doesn't match
    		if (!preg_match($checkEmail, $email)) {
    			$suspect = true;
    			$mailSent = false;
    			unset($missing);
    		}
    	}
    	
    // validate the comments  THIS IS MY LATEST IMPLEMENTATION THAT DOESN'T WORK
    	if (!empty($comments)) {
    		// regex to identify illegal characters in email address
    		$checkComments = '/(http:\/\/|www)/';
    		// reject the comments if link is found
    		if (!preg_match($checkComments, $comments)) {
    			$suspect = true;
    			$mailSent = false;
    			unset($missing);
    		}
    	}
    	
    	// go ahead only if not suspect and all required fields OK
    	if (!$suspect && empty($missing)) {
    		// initialize the $message variable
    		$message = '';
    		// loop through the $expected array
    		foreach($expected as $item) {
    			// assign the value of the current item to $val
    			if (isset(${$item})) {
    				$val = ${$item};
    			}
    			// if it has no value, assign 'Not Selected'
    			else {
    				$val = 'Not selected';
    			}
    			// if an array, expand as comma-separated string
    			if (is_array($val)) {
    				$val = implode(', ', $val);
    			}
    			// add label and value to the message body
    			$message .= ucfirst($item).": $val\n\n";
    			}
    	
    		// limit line length
    		$message = wordwrap($message, 70);
    		
    		// create Reply-To header
    		if (!empty($email)) {
    			$headers .= "\r\nReply-To: $email";
    		}
    	
    		// send it
    		$mailSent = mail($to, $subject, $message, $headers);
    		if ($mailSent) {
    			// $missing is no longer needed if the email is sent, so unset it
    			unset($missing);
    		}
    	}
      }
    ?>
    What I'd like to do is place the "link catcher" wherever, but have it reject the send process (mailSent) and as you can see in the regular page, throw a new error (checkLink) to say stop spamming the website.

    Thanks!!

  2. #2
    Join Date
    Jan 2004
    Posts
    484
    try this 1 for true 0 for false


    PHP Code:


    <?
    $pattern 
    "/\<a.*href=\"|\'(.*?)\"|\'.*?\>(.*)\<\/a\>+/i";


        

    //$inputString = '<a href="http://www.google.com">Google</a> <a Href="http://www.yahoo.com">Yahoo</a>';

    $inputString =  '<A HREF=\"http://msdn2.microsoft.com\">" +  "MSDN Home Page</A></P>' ;





    echo 
    preg_match($patternstripcslashes($inputString));



    ?>
    Natdrip :P
    "water go down the hole" - plucky duck

  3. #3
    Join Date
    Oct 2008
    Posts
    17
    Hi. I appreciate the response, but at this point I'm more concerned with the back-and-forth communication I have going than the pattern used to detect the link. The pattern that I have, though very simple, was working to catch a link but I'm running into syntax errors depending on where I implement it. If I put the "preg_match" into the actual form, I get conflicting errors (the correct error for submitting a link but at the top it still throws the message sent notification and the message is still sent). So what I'm looking for is help in getting the errors to display properly and to not allow the message to go any further if a link is found.

  4. #4
    Join Date
    Jan 2004
    Posts
    484
    Just use this
    PHP Code:
    if(preg_match($patternstripcslashes($inputString))){

    //if found a match return 

    }else{

    //if not then process


    Natdrip :P
    "water go down the hole" - plucky duck

  5. #5
    Join Date
    Oct 2008
    Posts
    17
    Thank you, Thank you, Thank you. Hopefully, this will stop the influx of spam until they figure out another way at least...

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles