Script 13.1 Filter Email Spam

Output

Say Hello

Contact Me

Source
<h1>Say Hello</h1>
<?php # Script 13.1 - email.php #2
// This version now scrubs dangerous strings from the submitted input.

// Check for form submission:
if ($_SERVER['REQUEST_METHOD'] == 'POST') {

	/* The function takes one argument: a string.
	* The function returns a clean version of the string.
	* The clean version may be either an empty string or
	* just the removal of all newline characters.
	*/
	function spam_scrubber($value) {

		// List of very bad values:
		$very_bad = array('to:', 'cc:', 'bcc:', 'content-type:', 'mime-version:', 'multipart-mixed:', 'content-transfer-encoding:');
	
		// If any of the very bad strings are in 
		// the submitted value, return an empty string:
		foreach ($very_bad as $v) {
			if (stripos($value, $v) !== false) return '';
		}
	
		// Replace any newline characters with spaces:
		$value = str_replace(array( "\r", "\n", "%0a", "%0d"), ' ', $value);
	
		// Return the value:
		return trim($value);

	} // End of spam_scrubber() function.

	// Clean the form data:
	$scrubbed = array_map('spam_scrubber', $_POST);

	// Minimal form validation:
	if (!empty($scrubbed['name']) && !empty($scrubbed['email']) && !empty($scrubbed['comments']) ) {
	
		// Create the body:
		$body = "Name: {$scrubbed['name']}\n\nComments: {$scrubbed['comments']}\n\nEmail: {$scrubbed['email']}";

		// Make it no longer than 70 characters long:
		$body = wordwrap($body, 70);
	
		// Send the email:
		mail('noreply@ashlietaylor.com', 'Script 13.1 Form Submission', $body, "From: {$scrubbed['email']}");

		// Print a message:
		echo '<div class="message">Thank you for submitting my form. I will never use your information - I promise!</div>';
		
		// Clear $scrubbed (so that the form's not sticky):
		$scrubbed = array();
	
	} else {
		echo '<p style="font-weight: bold; color: #C00">Please fill out the form completely.</p>';
	}
	
} // End of main isset() IF.

// Create the HTML form:
?>
<form action="" method="post">
	<fieldset><legend>Contact Me</legend>
		<p>
			<label for="n">Name: </label>
			<input id="n" type="text" name="name" size="30" maxlength="60" value="<?php if (isset($scrubbed['name'])) echo $scrubbed['name']; ?>" />
		</p>
		<p>
			<label for="e">Email Address: </label>
			<input id="e" type="text" name="email" size="30" maxlength="80" value="<?php if (isset($scrubbed['email'])) echo $scrubbed['email']; ?>" />
		</p>
		<p>
			<label for="c">Comments: </label>
			<textarea id="c" name="comments" rows="5" cols="30"><?php if (isset($scrubbed['comments'])) echo $scrubbed['comments']; ?></textarea>
		</p>
		<p>
			<input type="submit" name="submit" value="Send!" />
		</p>
	</fieldset>
</form>