title: Including contactform.php into HTML page error: Warning: Cannot modify header information - headers already sent
body: <blockquote>
    <p><strong>Possible Duplicate:</strong><br>
    <a href="https://stackoverflow.com/questions/8028957/headers-already-sent-by-php">Headers already sent by PHP</a>  </p>
  </blockquote>
  
  
  
  <p>I have been all over the internet trying to figure this out. There are about a million threads discussing this error, but none of them make it clear how to solve it.</p>
  
  <p>Here is what I am trying to accomplish, and I don't think it's that complicated.</p>
  
  <p>I want to put <a href="http://www.html-form-guide.com/contact-form/simple-php-contact-form.html" rel="nofollow noreferrer"><em>html-form-guide.com's contact form script <code>contactform.php</code><sup>&shy;link</sup></em></a> on an existing html page. I have already renamed it to .php and that's fine. The .php for the actual form submission is a seperate file, which I have included in the body section of my html with </p>
  
  <pre><code>&lt;?
    include ('contactform.php')
  ?&gt;
  </code></pre>
  
  <p>The contact form shows up fine, and you can enter everything fine. But when you click submit, you get the aforementioned error:</p>
  
  <pre><code>Warning: Cannot modify header information - headers already sent by... etc
  </code></pre>
  
  <p>When you click the submit button, another php script runs that validates everything and sends the email. This runs fine too, as emails are actually being sent. Then it is SUPPOSED to load a page that says thank you for your submission with this code:</p>
  
  <pre><code>function RedirectToURL($url)
  {
    header("Location: $url");
    exit;
  </code></pre>
  
  <p>But it doesn't, instead I get the error. It sounds like it is loading something from my main html page that actually displays the form, which is preventing this part from working. I have been to plenty of threads already that say you can't have any html or anything else displayed before the header command, but this doesn't really help me. I don't understand what else is being loaded, and far more importantly, I don't understand how to make it work. I vaguely understand the problem, what I don't at all understand is how to fix it.</p>
  
  <p>index.php
      
      
      
        
        
        
        
      </p>
  
  <pre><code>&lt;body&gt;
  &lt;div id="container"&gt;
      &lt;div id="header"&gt;
      &lt;p style="font-size:36px;"&gt;VoiceOverGenie.com&lt;/p&gt;
      &lt;/div&gt;
      &lt;div id="social"&gt;
          &lt;ul id="soclist"&gt;
              &lt;li&gt;&lt;a href="#"&gt;facebook&lt;/a&gt;&lt;/li&gt;
              &lt;li&gt;&lt;a href="#"&gt;twitter&lt;/a&gt;&lt;/li&gt;
              &lt;li&gt;&lt;a href="#"&gt;linkedin&lt;/a&gt;&lt;/li&gt;
              &lt;li&gt;&lt;a href="#"&gt;blog&lt;/a&gt;&lt;/li&gt;
          &lt;/ul&gt;
      &lt;/div&gt;
      &lt;?
        include ('contactform.php')
      ?&gt;
  
      &lt;div id="content"&gt;
      &lt;/div&gt;
  &lt;/div&gt;
  
  &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>
  
  <p>contactform.php</p>
  
  <pre><code>&lt;?PHP
  /*
      Contact Form from HTML Form Guide
      This program is free software published under the
      terms of the GNU Lesser General Public License.
      See this page for more info:
      http://www.html-form-guide.com/contact-form/simple-php-contact-form.html
  */
  require_once("./include/fgcontactform.php");
  
  $formproc = new FGContactForm();
  
  //1. Add your email address here.
  //You can add more than one receipients.
  $formproc-&gt;AddRecipient('test@test'); //&lt;&lt;---Put your email address here
  
  //2. For better security. Get a random tring from this link: http://tinyurl.com/randstr
  // and put it here
  $formproc-&gt;SetFormRandomKey('CnRrspl1FyEylUj');
  
  if(isset($_POST['submitted']))
  {
    if($formproc-&gt;ProcessForm())
    {
      $formproc-&gt;RedirectToURL("thank-you.php");
    }
  }
  
  ?&gt;
  &lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"&gt;
  &lt;html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US"&gt;
  &lt;head&gt;
    &lt;meta http-equiv='Content-Type' content='text/html; charset=utf-8'/&gt;
    &lt;title&gt;Contact us&lt;/title&gt;
    &lt;link rel="STYLESHEET" type="text/css" href="contact.css" /&gt;
    &lt;script type='text/javascript' src='scripts/gen_validatorv31.js'&gt;&lt;/script&gt;
  &lt;/head&gt;
  &lt;body&gt;
  
  &lt;!-- Form Code Start --&gt;
  &lt;form id='contactus' action='&lt;?php echo $formproc-&gt;GetSelfScript(); ?&gt;' method='post' accept-charset='UTF-8'&gt;
  &lt;fieldset &gt;
  &lt;legend&gt;Contact us&lt;/legend&gt;
  
  &lt;input type='hidden' name='submitted' id='submitted' value='1'/&gt;
  &lt;input type='hidden' name='&lt;?php echo $formproc-&gt;GetFormIDInputName(); ?&gt;' value='&lt;?php echo $formproc-&gt;GetFormIDInputValue(); ?&gt;'/&gt;
  &lt;input type='text'  class='spmhidip' name='&lt;?php echo $formproc-&gt;GetSpamTrapInputName(); ?&gt;' /&gt;
  
  &lt;div class='short_explanation'&gt;* required fields&lt;/div&gt;
  
  &lt;div&gt;&lt;span class='error'&gt;&lt;?php echo $formproc-&gt;GetErrorMessage(); ?&gt;&lt;/span&gt;&lt;/div&gt;
  &lt;div class='container'&gt;
      &lt;label for='name' &gt;Your Full Name*: &lt;/label&gt;&lt;br/&gt;
      &lt;input type='text' name='name' id='name' value='&lt;?php echo $formproc-&gt;SafeDisplay('name') ?&gt;' maxlength="50" /&gt;&lt;br/&gt;
      &lt;span id='contactus_name_errorloc' class='error'&gt;&lt;/span&gt;
  &lt;/div&gt;
  &lt;div class='container'&gt;
      &lt;label for='email' &gt;Email Address*:&lt;/label&gt;&lt;br/&gt;
      &lt;input type='text' name='email' id='email' value='&lt;?php echo $formproc-&gt;SafeDisplay('email') ?&gt;' maxlength="50" /&gt;&lt;br/&gt;
      &lt;span id='contactus_email_errorloc' class='error'&gt;&lt;/span&gt;
  &lt;/div&gt;
  &lt;div class='container'&gt;
      &lt;label for='phone' &gt;Phone Number*:&lt;/label&gt;&lt;br/&gt;
      &lt;input type='text' name='phone' id='phone' value='&lt;?php echo $formproc-&gt;SafeDisplay('phone') ?&gt;' maxlength="15" /&gt;&lt;br/&gt;
      &lt;span id='contactus_phone_errorloc' class='error'&gt;&lt;/span&gt;
  &lt;/div&gt;
  &lt;div class='container'&gt;
      &lt;label for='message' &gt;Message:&lt;/label&gt;&lt;br/&gt;
      &lt;span id='contactus_message_errorloc' class='error'&gt;&lt;/span&gt;
      &lt;textarea rows="10" cols="50" name='message' id='message'&gt;&lt;?php echo $formproc-&gt;SafeDisplay('message') ?&gt;&lt;/textarea&gt;
  &lt;/div&gt;
  
  
  &lt;div class='container'&gt;
      &lt;input type='submit' name='Submit' value='Submit' /&gt;
  &lt;/div&gt;
  
  &lt;/fieldset&gt;
  &lt;/form&gt;
  &lt;!-- client-side Form Validations:
  Uses the excellent form validation script from JavaScript-coder.com--&gt;
  
  &lt;script type='text/javascript'&gt;
  // &lt;![CDATA[
  
      var frmvalidator  = new Validator("contactus");
      frmvalidator.EnableOnPageErrorDisplay();
      frmvalidator.EnableMsgsTogether();
      frmvalidator.addValidation("name","req","Please provide your name");
  
      frmvalidator.addValidation("email","req","Please provide your email address");
  
      frmvalidator.addValidation("email","email","Please provide a valid email address");
  
      frmvalidator.addValidation("message","maxlen=2048","The message is too long!(more than 2KB!)");
  
      frmvalidator.addValidation("phone","req","Please provide your phone number");
  
  // ]]&gt;
  &lt;/script&gt;
  
  &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>
  
  <p>fgcontactform.php</p>
  
  <pre><code>&lt;?PHP
  /*
      Contact Form from HTML Form Guide
  
      This program is free software published under the
      terms of the GNU Lesser General Public License.
  
  This program is distributed in the hope that it will
  be useful - WITHOUT ANY WARRANTY; without even the
  implied warranty of MERCHANTABILITY or FITNESS FOR A
  PARTICULAR PURPOSE.
  
  @copyright html-form-guide.com 2010
  */
  require_once("class.phpmailer.php");
  
  /*
  Interface to Captcha handler
  */
  class FG_CaptchaHandler
  {
      function Validate() { return false;}
      function GetError(){ return '';}
  }
  /*
  FGContactForm is a general purpose contact form class
  It supports Captcha, HTML Emails, sending emails
  conditionally, File atachments and more.
  */
  class FGContactForm
  {
      var $receipients;
      var $errors;
      var $error_message;
      var $name;
      var $email;
      var $message;
      var $from_address;
      var $form_random_key;
      var $conditional_field;
      var $arr_conditional_receipients;
      var $fileupload_fields;
      var $captcha_handler;
  
      var $mailer;
  
      function FGContactForm()
      {
          $this-&gt;receipients = array();
          $this-&gt;errors = array();
          $this-&gt;form_random_key = 'HTgsjhartag';
          $this-&gt;conditional_field='';
          $this-&gt;arr_conditional_receipients=array();
          $this-&gt;fileupload_fields=array();
  
          $this-&gt;mailer = new PHPMailer();
          $this-&gt;mailer-&gt;CharSet = 'utf-8';
      }
  
      function EnableCaptcha($captcha_handler)
      {
          $this-&gt;captcha_handler = $captcha_handler;
          session_start();
      }
  
      function AddRecipient($email,$name="")
      {
          $this-&gt;mailer-&gt;AddAddress($email,$name);
      }
  
      function SetFromAddress($from)
      {
          $this-&gt;from_address = $from;
      }
      function SetFormRandomKey($key)
      {
          $this-&gt;form_random_key = $key;
      }
      function GetSpamTrapInputName()
      {
          return 'sp'.md5('KHGdnbvsgst'.$this-&gt;GetKey());
      }
      function SafeDisplay($value_name)
      {
          if(empty($_POST[$value_name]))
          {
              return'';
          }
          return htmlentities($_POST[$value_name]);
      }
      function GetFormIDInputName()
      {
          $rand = md5('TygshRt'.$this-&gt;GetKey());
  
          $rand = substr($rand,0,20);
          return 'id'.$rand;
      }
  
  
      function GetFormIDInputValue()
      {
          return md5('jhgahTsajhg'.$this-&gt;GetKey());
      }
  
      function SetConditionalField($field)
      {
          $this-&gt;conditional_field = $field;
      }
      function AddConditionalReceipent($value,$email)
      {
          $this-&gt;arr_conditional_receipients[$value] =  $email;
      }
  
      function AddFileUploadField($file_field_name,$accepted_types,$max_size)
      {
  
          $this-&gt;fileupload_fields[] =
              array("name"=&gt;$file_field_name,
              "file_types"=&gt;$accepted_types,
              "maxsize"=&gt;$max_size);
      }
  
      function ProcessForm()
      {
          if(!isset($_POST['submitted']))
          {
             return false;
          }
          if(!$this-&gt;Validate())
          {
              $this-&gt;error_message = implode('&lt;br/&gt;',$this-&gt;errors);
              return false;
          }
          $this-&gt;CollectData();
  
          $ret = $this-&gt;SendFormSubmission();
  
          return $ret;
      }
  
      function RedirectToURL($url)
      {
          header("Location: $url");
          exit;
      }
  
      function GetErrorMessage()
      {
          return $this-&gt;error_message;
      }
      function GetSelfScript()
      {
          return htmlentities($_SERVER['PHP_SELF']);
      }
  
      function GetName()
      {
          return $this-&gt;name;
      }
      function GetEmail()
      {
          return $this-&gt;email;
      }
      function GetMessage()
      {
          return htmlentities($this-&gt;message,ENT_QUOTES,"UTF-8");
      }
  
  /*--------  Private (Internal) Functions -------- */
  
  
      function SendFormSubmission()
      {
          $this-&gt;CollectConditionalReceipients();
  
          $this-&gt;mailer-&gt;CharSet = 'utf-8';
  
          $this-&gt;mailer-&gt;Subject = "Contact form submission from $this-&gt;name";
  
          $this-&gt;mailer-&gt;From = $this-&gt;GetFromAddress();
  
          $this-&gt;mailer-&gt;FromName = $this-&gt;name;
  
          $this-&gt;mailer-&gt;AddReplyTo($this-&gt;email);
  
          $message = $this-&gt;ComposeFormtoEmail();
  
          $textMsg = trim(strip_tags(preg_replace('/&lt;(head|title|style|script)[^&gt;]*&gt;.*?&lt;\/\\1&gt;/s','',$message)));
          $this-&gt;mailer-&gt;AltBody = @html_entity_decode($textMsg,ENT_QUOTES,"UTF-8");
          $this-&gt;mailer-&gt;MsgHTML($message);
  
          $this-&gt;AttachFiles();
  
          if(!$this-&gt;mailer-&gt;Send())
          {
              $this-&gt;add_error("Failed sending email!");
              return false;
          }
  
          return true;
      }
  
      function CollectConditionalReceipients()
      {
          if(count($this-&gt;arr_conditional_receipients)&gt;0 &amp;&amp;
            !empty($this-&gt;conditional_field) &amp;&amp;
            !empty($_POST[$this-&gt;conditional_field]))
          {
              foreach($this-&gt;arr_conditional_receipients as $condn =&gt; $rec)
              {
                  if(strcasecmp($condn,$_POST[$this-&gt;conditional_field])==0 &amp;&amp;
                  !empty($rec))
                  {
                      $this-&gt;AddRecipient($rec);
                  }
              }
          }
      }
  
      /*
      Internal variables, that you donot want to appear in the email
      Add those variables in this array.
      */
      function IsInternalVariable($varname)
      {
          $arr_interanl_vars = array('scaptcha',
                              'submitted',
                              $this-&gt;GetSpamTrapInputName(),
                              $this-&gt;GetFormIDInputName()
                              );
          if(in_array($varname,$arr_interanl_vars))
          {
              return true;
          }
          return false;
      }
  
      function FormSubmissionToMail()
      {
          $ret_str='';
          foreach($_POST as $key=&gt;$value)
          {
              if(!$this-&gt;IsInternalVariable($key))
              {
                  $value = htmlentities($value,ENT_QUOTES,"UTF-8");
                  $value = nl2br($value);
                  $key = ucfirst($key);
                  $ret_str .= "&lt;div class='label'&gt;$key :&lt;/div&gt;&lt;div class='value'&gt;$value &lt;/div&gt;\n";
              }
          }
          foreach($this-&gt;fileupload_fields as $upload_field)
          {
              $field_name = $upload_field["name"];
              if(!$this-&gt;IsFileUploaded($field_name))
              {
                  continue;
              }        
  
              $filename = basename($_FILES[$field_name]['name']);
  
              $ret_str .= "&lt;div class='label'&gt;File upload '$field_name' :&lt;/div&gt;&lt;div class='value'&gt;$filename &lt;/div&gt;\n";
          }
          return $ret_str;
      }
  
      function ExtraInfoToMail()
      {
          $ret_str='';
  
          $ip = $_SERVER['REMOTE_ADDR'];
          $ret_str = "&lt;div class='label'&gt;IP address of the submitter:&lt;/div&gt;&lt;div class='value'&gt;$ip&lt;/div&gt;\n";
  
          return $ret_str;
      }
  
      function GetMailStyle()
      {
          $retstr = "\n&lt;style&gt;".
          "body,.label,.value { font-family:Arial,Verdana; } ".
          ".label {font-weight:bold; margin-top:5px; font-size:1em; color:#333;} ".
          ".value {margin-bottom:15px;font-size:0.8em;padding-left:5px;} ".
          "&lt;/style&gt;\n";
  
          return $retstr;
      }
      function GetHTMLHeaderPart()
      {
           $retstr = '&lt;!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"&gt;'."\n".
                     '&lt;html&gt;&lt;head&gt;&lt;title&gt;&lt;/title&gt;'.
                     '&lt;meta http-equiv=Content-Type content="text/html; charset=utf-8"&gt;';
           $retstr .= $this-&gt;GetMailStyle();
           $retstr .= '&lt;/head&gt;&lt;body&gt;';
           return $retstr;
      }
      function GetHTMLFooterPart()
      {
          $retstr ='&lt;/body&gt;&lt;/html&gt;';
          return $retstr ;
      }
      function ComposeFormtoEmail()
      {
          $header = $this-&gt;GetHTMLHeaderPart();
          $formsubmission = $this-&gt;FormSubmissionToMail();
          $extra_info = $this-&gt;ExtraInfoToMail();
          $footer = $this-&gt;GetHTMLFooterPart();
  
          $message = $header."Submission from 'contact us' form:&lt;p&gt;$formsubmission&lt;/p&gt;&lt;hr/&gt;$extra_info".$footer;
  
          return $message;
      }
  
      function AttachFiles()
      {
          foreach($this-&gt;fileupload_fields as $upld_field)
          {
              $field_name = $upld_field["name"];
              if(!$this-&gt;IsFileUploaded($field_name))
              {
                  continue;
              }
  
              $filename =basename($_FILES[$field_name]['name']);
  
              $this-&gt;mailer-&gt;AddAttachment($_FILES[$field_name]["tmp_name"],$filename);
          }
      }
  
      function GetFromAddress()
      {
          if(!empty($this-&gt;from_address))
          {
              return $this-&gt;from_address;
          }
  
          $host = $_SERVER['SERVER_NAME'];
  
          $from ="nobody@$host";
          return $from;
      }
  
      function Validate()
      {
          $ret = true;
          //security validations
          if(empty($_POST[$this-&gt;GetFormIDInputName()]) ||
            $_POST[$this-&gt;GetFormIDInputName()] != $this-&gt;GetFormIDInputValue() )
          {
              //The proper error is not given intentionally
              $this-&gt;add_error("Automated submission prevention: case 1 failed");
              $ret = false;
          }
  
          //This is a hidden input field. Humans won't fill this field.
          if(!empty($_POST[$this-&gt;GetSpamTrapInputName()]) )
          {
              //The proper error is not given intentionally
              $this-&gt;add_error("Automated submission prevention: case 2 failed");
              $ret = false;
          }
  
          //name validations
          if(empty($_POST['name']))
          {
              $this-&gt;add_error("Please provide your name");
              $ret = false;
          }
          else
          if(strlen($_POST['name'])&gt;50)
          {
              $this-&gt;add_error("Name is too big!");
              $ret = false;
          }
  
          //email validations
          if(empty($_POST['email']))
          {
              $this-&gt;add_error("Please provide your email address");
              $ret = false;
          }
          else
          if(strlen($_POST['email'])&gt;50)
          {
              $this-&gt;add_error("Email address is too big!");
              $ret = false;
          }
          else
          if(!$this-&gt;validate_email($_POST['email']))
          {
              $this-&gt;add_error("Please provide a valid email address");
              $ret = false;
          }
  
          //message validaions
          if(strlen($_POST['message'])&gt;2048)
          {
              $this-&gt;add_error("Message is too big!");
              $ret = false;
          }
  
          //captcha validaions
          if(isset($this-&gt;captcha_handler))
          {
              if(!$this-&gt;captcha_handler-&gt;Validate())
              {
                  $this-&gt;add_error($this-&gt;captcha_handler-&gt;GetError());
                  $ret = false;
              }
          }
          //file upload validations
          if(!empty($this-&gt;fileupload_fields))
          {
           if(!$this-&gt;ValidateFileUploads())
           {
              $ret = false;
           }
          }
          return $ret;
      }
  
      function ValidateFileType($field_name,$valid_filetypes)
      {
          $ret=true;
          $info = pathinfo($_FILES[$field_name]['name']);
          $extn = $info['extension'];
          $extn = strtolower($extn);
  
          $arr_valid_filetypes= explode(',',$valid_filetypes);
          if(!in_array($extn,$arr_valid_filetypes))
          {
              $this-&gt;add_error("Valid file types are: $valid_filetypes");
              $ret=false;
          }
          return $ret;
      }
  
      function ValidateFileSize($field_name,$max_size)
      {
          $size_of_uploaded_file =
                  $_FILES[$field_name]["size"]/1024;//size in KBs
          if($size_of_uploaded_file &gt; $max_size)
          {
              $this-&gt;add_error("The file is too big. File size should be less than $max_size KB");
              return false;
          }
          return true;
      }
  
      function IsFileUploaded($field_name)
      {
          if(empty($_FILES[$field_name]['name']))
          {
              return false;
          }
          if(!is_uploaded_file($_FILES[$field_name]['tmp_name']))
          {
              return false;
          }
          return true;
      }
      function ValidateFileUploads()
      {
          $ret=true;
          foreach($this-&gt;fileupload_fields as $upld_field)
          {
              $field_name = $upld_field["name"];
  
              $valid_filetypes = $upld_field["file_types"];
  
              if(!$this-&gt;IsFileUploaded($field_name))
              {
                  continue;
              }
  
              if($_FILES[$field_name]["error"] != 0)
              {
                  $this-&gt;add_error("Error in file upload; Error code:".$_FILES[$field_name]["error"]);
                  $ret=false;
              }
  
              if(!empty($valid_filetypes) &amp;&amp;
               !$this-&gt;ValidateFileType($field_name,$valid_filetypes))
              {
                  $ret=false;
              }
  
              if(!empty($upld_field["maxsize"]) &amp;&amp;
              $upld_field["maxsize"]&gt;0)
              {
                  if(!$this-&gt;ValidateFileSize($field_name,$upld_field["maxsize"]))
                  {
                      $ret=false;
                  }
              }
  
          }
          return $ret;
      }
  
      function StripSlashes($str)
      {
          if(get_magic_quotes_gpc())
          {
              $str = stripslashes($str);
          }
          return $str;
      }
      /*
      Sanitize() function removes any potential threat from the
      data submitted. Prevents email injections or any other hacker attempts.
      if $remove_nl is true, newline chracters are removed from the input.
      */
      function Sanitize($str,$remove_nl=true)
      {
          $str = $this-&gt;StripSlashes($str);
  
          if($remove_nl)
          {
              $injections = array('/(\n+)/i',
                  '/(\r+)/i',
                  '/(\t+)/i',
                  '/(%0A+)/i',
                  '/(%0D+)/i',
                  '/(%08+)/i',
                  '/(%09+)/i'
                  );
              $str = preg_replace($injections,'',$str);
          }
  
          return $str;
      }
  
      /*Collects clean data from the $_POST array and keeps in internal variables.*/
      function CollectData()
      {
          $this-&gt;name = $this-&gt;Sanitize($_POST['name']);
          $this-&gt;email = $this-&gt;Sanitize($_POST['email']);
  
          /*newline is OK in the message.*/
          $this-&gt;message = $this-&gt;StripSlashes($_POST['message']);
      }
  
      function add_error($error)
      {
          array_push($this-&gt;errors,$error);
      }
      function validate_email($email)
      {
          return eregi("^[_\.0-9a-zA-Z-]+@([0-9a-zA-Z][0-9a-zA-Z-]+\.)+[a-zA-Z]{2,6}$", $email);
      }
  
      function GetKey()
      {
          return $this-&gt;form_random_key.$_SERVER['SERVER_NAME'].$_SERVER['REMOTE_ADDR'];
      }
  
  }
  
  ?&gt;
  </code></pre>