How to prevent form hijacked/spam injection?

Frequently Asked Questions about WYSIWYG Web Builder
User avatar
Posts: 23393
Joined: Tue Mar 28, 2006 12:00 pm
Location: Europe

How to prevent form hijacked/spam injection?

Post by Pablo » Sat Sep 16, 2006 3:19 pm

A common problem with online forms is that hackers try to hijacked it to send spam. This article introduces a possible solution to prevent this.
The article extends our previous solution 'How do I use PHP to collect form data?'
So be sure to read that first!

The following modifications where made to the previous solution:
1. If the script was not activated by a form-POST it will be redirected to an URL of your choice. Replace '/index.html' with your own landing page.
2. The function 'Valid_Input' validates if header fields do not contain any 'injected' code like 'CC:', 'BCC:' etc.
3. The function 'Valid_Email' validates the e-mailadres. It prevents email ranges or other illegal data.
4. A couple of extra header fields where added to decrease the chance that the generated email is marked as spam by spam-filters.

The following code replaces the previously feedback.php code:

Code: Select all

    header('Refresh: 0; URL=/index.html');

  $mailto  = "";
  $subject = "Feedback form";
  $message = "Values submitted from web site form:";
  $name    = Valid_Input($_POST['name']);
  $email   = Valid_Email($_POST['email']);
  foreach ($_POST as $key => $value){
    if (!is_array($value)){
      $message .= "\n".$key." : ".$value;
      foreach ($_POST[$key] as $itemvalue){
        $message .= "\n".$key." : ".$itemvalue;
  $header  = "From: ".$name." <".$email.">\n";
  $header .= "Reply-To: ".$email."\n";
  $header .= "MIME-Version: 1.0\n";
  $header .= "Content-Type: text/plain; charset=utf-8\n";
  $header .= "Content-Transfer-Encoding: 8bit\n";
  $header .= "X-Mailer: PHP v".phpversion();

  mail($mailto, $subject, stripslashes($message), $header) or exit('Fatal Mail Error!');

  function Valid_Input($data){
    list($data) = preg_split('/\r|\n|%0A|%0D|0x0A|0x0D/i',ltrim($data));
    return $data;
  function Valid_Email($data){
    $pattern = '/^([0-9a-z]([-.\w]*[0-9a-z])*@(([0-9a-z])+([-\w]*[0-9a-z])*\.)+[a-z]{2,6})$/i';
    if (preg_match($pattern,$data)){
      return $data;
      return $GLOBALS['mailto'];
The updated example can be dowloaded here: ...

Thanks to Kees for providing this solution!