Mail Form Email Header Injection

A while back, I saw some mail form email injection attacks hitting my contact form. This was easy to filter for (replace \n’s and \r’s for the headers; also PHPMailer didn’t seem to be be affected by the MIME handling attack), but the continued daily probing has quickly gotten annoying. So, I adapted my IP minefielding code, and now, if you try to inject, you get slapped:

// Test for annoyance
foreach($_POST as $field => $input) {
  $input = stripslashes($input);
  if(preg_match('/Content-Type: multipart\/mixed/i', $input)) $attack++;
  if($field != 'body') {
    if(preg_match('/\n/', $input)) $attack++;
    if(preg_match('/\r/', $input))  $attack++;  
  }
}

if($attack) {  
  $deny = '# ' . date("D M j G:i:s T Y") . "\n";
  $deny .= 'Deny from ' . $_SERVER['REMOTE_ADDR'] . "\n";
  fwrite(fopen('.htaccess', 'a'),$deny);  
  print "You've been detected trying to do stream injection and blocked from further access to this mail form.";  
  exit;
}