24 Replies Latest reply on Feb 10, 2016 3:16 AM by osgood_

    error says: Warning: Cannot modify header information

    BrennaLee Level 1

      I keep receiving an error message after my form is sent (the form still send the information I need just wont re-direct to the next page)

       

      It redirects to a page that says:

       

      Warning: Cannot modify header information - headers already sent by (output started at /home/tommyle/public_html/newp.php:10) in /home/tommyle/public_html/newp.php on line 41


      my php code looks like this:

       

      <!doctype html>

      <html>

      <head>

      <meta charset="utf-8">

      <title>Tommy Lemonade Beta</title>

      <link href="style1.css" rel="stylesheet" type="text/css">

      </head>

       

       

      <body>

      <?php

      /* Set e-mail recipient */

      $myemail = "profiles@tommylemonade";

       

       

      /* Check all form inputs using check_input function */

      $name = check_input($_POST['name'], "Enter your name");

      $subject = check_input($_POST['subject'], "Enter a subject");

      $email = check_input($_POST['email']);

      $message = check_input($_POST['message'], "Write your message");

       

       

      /* If e-mail is not valid show error message */

      if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/", $email))

      {

      show_error("E-mail address not valid");

      }

      /* Let's prepare the message for the e-mail */

      $message = "

       

       

      Name: $name

      E-mail: $email

      Subject: $subject

       

       

      Message:

      $message

       

       

      ";

       

       

      /* Send the message using mail() function */

      mail($myemail, $subject, $message);

       

       

      /* Redirect visitor to the thank you page */

      header('Location: thanks.html');

      exit();

       

       

      /* Functions we used */

      function check_input($data, $problem='')

      {

      $data = trim($data);

      $data = stripslashes($data);

      $data = htmlspecialchars($data);

      if ($problem && strlen($data) == 0)

      {

      show_error($problem);

      }

      return $data;

      }

       

       

      function show_error($myError)

      {

      ?>

      <html>

      <body>

       

       

      <p>Please correct the following error:</p>

      <strong><?php echo $myError; ?></strong>

      <p>Hit the back button and try again</p>

       

       

      </body>

      </html>

      <?php

      exit();

      }

      ?>

      </body>

      </html>

       

       

       

      This is line 41:

       

      header('Location: thanks.html');

       

       

       

      Can anybody see what I'm missing?

        • 1. Re: error says: Warning: Cannot modify header information
          osgood_ Level 8

          One cause of that error is any white line spaces between the php coding. The main cause though is if anything is output to the page before the execution of the php 'header' line.

           

          Close up any white line spacing first and test again.

          • 2. Re: error says: Warning: Cannot modify header information
            Rob Hecker2 Adobe Community Professional & MVP

            White spacing is not an issue, but Osgood is right on the other point.

             

            The whole block of code from <!doctype html> to <body> needs to go below header(Location, but that's not the only problem you are going to have. Make sure you have only one pair of <body) tags, etc. and make sure header(Location is within PHP script tags.

            • 3. Re: error says: Warning: Cannot modify header information
              osgood_ Level 8

              Yeah, rework the code so you don't get any output before the php code is executed (like below):

               

               

               

              <?php

              /* Set e-mail recipient */

              $myemail = "profiles@tommylemonade";

              /* Check all form inputs using check_input function */

              $name = check_input($_POST['name'], "Enter your name");

              $subject = check_input($_POST['subject'], "Enter a subject");

              $email = check_input($_POST['email']);

              $message = check_input($_POST['message'], "Write your message");

              /* If e-mail is not valid show error message */

              if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/", $email))

              {

              show_error("E-mail address not valid");

              }

              /* Let's prepare the message for the e-mail */

              $message = "

              Name: $name

              E-mail: $email

              Subject: $subject

              Message: $message

              ";

              /* Send the message using mail() function */

              mail($myemail, $subject, $message);

              /* Redirect visitor to the thank you page */

              header('Location: thanks.html');

              exit();

              /* Functions we used */

              function check_input($data, $problem='')

              {

              $data = trim($data);

              $data = stripslashes($data);

              $data = htmlspecialchars($data);

              if ($problem && strlen($data) == 0)

              {

              show_error($problem);

              }

              return $data;

              }

              function show_error($myError)

              {

              ?>

              <!doctype html>

              <html>

              <head>

              <meta charset="utf-8">

              <title>Tommy Lemonade Beta</title>

              <link href="style1.css" rel="stylesheet" type="text/css">

              </head>

              <body>

              <p>Please correct the following error:</p>

              <strong><?php echo $myError; ?></strong>

              <p>Hit the back button and try again</p>

              </body>

              </html>

              <?php

              exit();

              }

              ?>

              1 person found this helpful
              • 4. Re: error says: Warning: Cannot modify header information
                Susan_at_Akuaba Level 1

                I am not feeling clever about this as nothing seems to correct this same above message for me.

                 

                 

                Warning: Cannot modify header information - headers already sent by (output started at /home/content/a/d/o/adonis/html/2016/Questions.php:10) in /home/content/a/d/o/adonis/html/2016/Questions.php on line 46

                 

                Line 46 is

                 

                 

                header('Location: thanks.htm');

                 

                Can I just have a message appear when the form results have been posted to me instead of going to a separate page.  Would that be easier?  Could the problem be with GoDaddy's way of dealing with PHP forms?

                 

                The whole code is now:

                 

                <?php

                /* Set e-mail recipient */

                $myemail  = "jcoe@bigpond.net.au";

                /* Check all form inputs using check_input function */

                $yourname = check_input($_POST['yourname'], "Enter your name");

                $subject  = check_input($_POST['subject'], "Write a subject");

                $email    = check_input($_POST['email']);

                $website  = check_input($_POST['website']);

                $likeit   = check_input($_POST['likeit']);

                $how_find = check_input($_POST['how']);

                $comments = check_input($_POST['comments'], "Write your comments");

                /* If e-mail is not valid show error message */

                if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/", $email))

                {

                    show_error("E-mail address not valid");

                }

                /* If URL is not valid set $website to empty */

                if (!preg_match("/^(https?:\/\/+[\w\-]+\.[\w\-]+)/i", $website))

                {

                    $website = '';

                }

                /* Let's prepare the message for the e-mail */

                $message = "Hello!

                Your contact form has been submitted by:

                Name: $yourname

                E-mail: $email

                URL: $website

                Like the website? $likeit

                How did he/she find it? $how_find

                Comments:

                $comments

                End of message

                ";

                /* Send the message using mail() function */

                mail($myemail, $subject, $message);

                /* Redirect visitor to the thank you page */

                header('Location: thanks.htm');

                exit();

                /* Functions we used */

                function check_input($data, $problem='')

                {

                    $data = trim($data);

                    $data = stripslashes($data);

                    $data = htmlspecialchars($data);

                    if ($problem && strlen($data) == 0)

                    {

                        show_error($problem);

                    }

                    return $data;

                }

                function show_error($myError)

                {

                ?>

                    <html>

                    <body>

                    <b>Please correct the following error:</b><br />

                    <?php echo $myError; ?>

                    </body>

                    </html>

                <?php

                exit();

                }

                ?>

                 

                • 5. Re: error says: Warning: Cannot modify header information
                  BenPleysier Adobe Community Professional & MVP

                  As @osgood_ has correctly stated, output has already been sent output prior to executing the header command.

                   

                  One way out of this is to replace

                   

                  header('Location: thanks.htm');

                   

                  with JavaScript like

                  echo "<script>location.href = 'thanks.htm'</script>";

                  the

                  • 6. Re: error says: Warning: Cannot modify header information
                    David_Powers Adobe Community Professional (Moderator)

                    Susan_at_Akuaba wrote:

                     

                    Warning: Cannot modify header information - headers already sent by (output started at /home/content/a/d/o/adonis/html/2016/Questions.php:10) in /home/content/a/d/o/adonis/html/2016/Questions.php on line 46

                     

                    Line 46 is

                    Line 46 is not where the error is. The error message tells you where the problem lies (although it's not very intuitive).

                     

                    This is the relevant part of the error message: output started at /home/content/a/d/o/adonis/html/2016/Questions.php:10

                     

                    In other words, the problem lies on line 10 of Questions.php.

                    • 7. Re: error says: Warning: Cannot modify header information
                      David_Powers Adobe Community Professional (Moderator)

                      For more information, see this ancient (but still relevant) article that I wrote: PHP development: why redirects don't work (headers already sent).

                      • 8. Re: error says: Warning: Cannot modify header information
                        Level 4

                        David_Powers wrote:

                        Susan_at_Akuaba wrote:

                         

                        Warning: Cannot modify header information - headers already sent by (output started at /home/content/a/d/o/adonis/html/2016/Questions.php:10) in /home/content/a/d/o/adonis/html/2016/Questions.php on line 46

                         

                        Line 46 is

                        Line 46 is not where the error is. The error message tells you where the problem lies (although it's not very intuitive).

                         

                        This is the relevant part of the error message: output started at /home/content/a/d/o/adonis/html/2016/Questions.php:10

                         

                        In other words, the problem lies on line 10 of Questions.php.

                         

                        If Line 46 of /home/content/a/d/o/adonis/html/2016/Questions.php is header('Location: thanks.htm'); then Line 10 of /home/content/a/d/o/adonis/html/2016/Questions.php would be the first line provided by the poster. So Line 10 of /home/content/a/d/o/adonis/html/2016/Questions.php is the following:


                        <?php

                         

                        My guess is that the error is occurring because line 1-9 of Questions.php has doctype and meta tags.

                         

                        best,

                        Shocker

                        • 9. Re: error says: Warning: Cannot modify header information
                          David_Powers Adobe Community Professional (Moderator)

                          the_shocker wrote:

                           

                          My guess is that the error is occurring because line 1-9 of Questions.php has doctype and meta tags.

                          If that were the case, I'm pretty sure the error message would say that output began on line 1, not line 10.

                           

                          The OP says "the whole code is..." Counting lines posted into the forum isn't always accurate. I suspect there is probably white space or a byte order mark (BOM) before the opening PHP tag, but without seeing the actual file, it's pure guesswork.

                           

                          It's common these days for PHP installations to set output_buffering to 4096 to avoid this type of problem. I know that XAMPP does, which could explain why the form works correctly locally, but not on the live server.

                          • 10. Re: error says: Warning: Cannot modify header information
                            osgood_ Level 8

                            'Cannot modifiy header information' has always been a bit of a PITA.

                             

                            I now make sure nothing is output before the line appears in the php code and that I have no space before the <?php ?> blocks or if that fails I remove any space I can find just to be sure.

                             

                            Or use Bens suggestion - I seem to remember it's not good practice to do so because some may have js turned off but hey if it works - it works and who cares about the minority that do have js turned off. They must be having a real 1990s experience. 

                             

                            Os

                            • 11. Re: error says: Warning: Cannot modify header information
                              David_Powers Adobe Community Professional (Moderator)

                              Fixing the problem of "Cannot modify header information" is very simple. Use the error message to identify where the output started, and remove the problem.

                               

                              One of the most common causes is whitespace after the closing PHP tag of an include file. That's not the case here, but it can always be fixed by omitting the closing PHP tag of files that contain only PHP script. In fact, that's what the PHP documentation recommends.

                               

                              If the cause of the problem isn't obvious from reviewing the script, it's almost certainly caused by the script beginning with the (invisible) byte order mark (BOM). You can remove the BOM in Dreamweaver by going to Modify > Page Properties > Title/Encoding and deselecting the BOM check box. By default, Dreamweaver does not insert the BOM in PHP files, so it shouldn't be an issue.

                               

                              If you can't find the cause of the problem (unlikely), the simple solution on servers that support .htaccess is to add the following to the .htaccess file:

                               

                              php_value output_buffering 4096

                              • 12. Re: error says: Warning: Cannot modify header information
                                osgood_ Level 8

                                David_Powers wrote:

                                 

                                Fixing the problem of "Cannot modify header information" is very simple.

                                 

                                I think once you've encountered it a couple of times it is easy to identify and fix, one way or another. I have no problem now because I'm aware of it and the optional fixes/workaround. Like most things it's a learning curve.

                                 

                                Google for "Cannot modify header information", seems to have caused an awful lot of developers an awful lot of problems.

                                • 13. Re: error says: Warning: Cannot modify header information
                                  David_Powers Adobe Community Professional (Moderator)

                                  osgood_ wrote:

                                   

                                  Google for "Cannot modify header information", seems to have caused and awful lot of developers an awful lot of problems.

                                  I don't deny that. I remember it causing me major headaches in the early days when I was learning. I used the excellent PHP & MySQL Web Development by Welling and Thomson. I don't recall it ever mentioning the issue of "headers cannot be modified". If it was, it was buried among other information, so didn't leap out. As a result, I've always highlighted the problem in my books and video courses for beginners.

                                   

                                  As I said before, one of the main causes is whitespace after the closing PHP tag in an include file. I think the problem is that beginners have it drummed into them that PHP code goes between opening and closing tags. For many years, I always used a closing tag, but I don't any more. If the script contains only PHP code, the closing tag can trigger unexpected problems. Leave it out. You need the closing tag only if the PHP is embedded in HTML or other code.

                                  • 14. Re: error says: Warning: Cannot modify header information
                                    osgood_ Level 8

                                    David_Powers wrote:

                                     

                                    osgood_ wrote:

                                     

                                    Google for "Cannot modify header information", seems to have caused and awful lot of developers an awful lot of problems.

                                    I think the problem is that beginners have it drummed into them that PHP code goes between opening and closing tags. For many years, I always used a closing tag, but I don't any more. If the script contains only PHP code, the closing tag can trigger unexpected problems. Leave it out. You need the closing tag only if the PHP is embedded in HTML or other code.

                                     

                                    Old habits die hard - I still using closing tags.

                                    • 15. Re: error says: Warning: Cannot modify header information
                                      Level 4

                                      David_Powers wrote:

                                       

                                      the_shocker wrote:

                                       

                                      My guess is that the error is occurring because line 1-9 of Questions.php has doctype and meta tags.

                                      If that were the case, I'm pretty sure the error message would say that output began on line 1, not line 10.

                                       

                                       

                                      I'm not buying that. Original post of this thread had a similar issue with doctype, meta, and html tags before php location redirect, yet the error message for the original poster said the output started on line 10, not line 1.

                                       

                                      Just to prove my point I created a simple page with doctype, meta, and other tags on line 1-7 with an embedded php script starting at line 8 that contains a location redirect (see code below). Can you guess where the error message said the output started? You said you were pretty sure the error message would say that output began on line 1, but alas, the error message from the code below says output started on line 8.

                                       

                                      My guess is that when the OP said "the whole code is..." they really meant "the whole PHP code that's assumed to pertain to the error message is...", while omitting the non-php code that occurred before the php code. They probably omitted code before the php code because they figured it was a php error displaying so they decided to show only the php code that they thought was relevant.

                                       

                                      <!doctype html>
                                      <html>
                                      <head>
                                      <meta charset="utf-8">
                                      <title>Where Does The Output Start?</title>
                                      </head>
                                      <body>
                                          <?php
                                              // Redirect visitor to Google
                                              header('Location: http://google.com');
                                              exit();
                                          ?>
                                      </body>
                                      </html>
                                      
                                      

                                       

                                      best,

                                      Shocker

                                      1 person found this helpful
                                      • 16. Re: error says: Warning: Cannot modify header information
                                        David_Powers Adobe Community Professional (Moderator)

                                        OK, fine. That's both interesting and useful to know. I normally run a test if I'm not sure, but I was just about to go out for the rest of the day, so didn't have time. Thanks for doing the experiment.

                                        • 17. Re: error says: Warning: Cannot modify header information
                                          Susan_at_Akuaba Level 1

                                          With all blank lines removed Line 10 is

                                          <?php

                                          and Line 46 is

                                          header('Location: thanks.htm');

                                           

                                          The actual entire code for the page is:

                                           

                                          <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

                                          <html xmlns="http://www.w3.org/1999/xhtml">

                                          <head>

                                          <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

                                          <title>Untitled Document</title>

                                          </head>

                                          <body>

                                          </body>

                                          </html>

                                          <?php

                                          /* Set e-mail recipient */

                                          $myemail  = "jcoe@bigpond.net.au";

                                          /* Check all form inputs using check_input function */

                                          $yourname = check_input($_POST['yourname'], "Enter your name");

                                          $subject  = check_input($_POST['subject'], "Write a subject");

                                          $email    = check_input($_POST['email']);

                                          $website  = check_input($_POST['website']);

                                          $likeit   = check_input($_POST['likeit']);

                                          $how_find = check_input($_POST['how']);

                                          $comments = check_input($_POST['comments'], "Write your comments");

                                          /* If e-mail is not valid show error message */

                                          if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/", $email))

                                          {

                                              show_error("E-mail address not valid");

                                          }

                                          /* If URL is not valid set $website to empty */

                                          if (!preg_match("/^(https?:\/\/+[\w\-]+\.[\w\-]+)/i", $website))

                                          {

                                              $website = '';

                                          }

                                          /* Let's prepare the message for the e-mail */

                                          $message = "Hello!

                                          Your contact form has been submitted by:

                                          Name: $yourname

                                          E-mail: $email

                                          URL: $website

                                          Like the website? $likeit

                                          How did he/she find it? $how_find

                                          Comments:

                                          $comments

                                          End of message

                                          ";

                                          /* Send the message using mail() function */

                                          mail($myemail, $subject, $message);

                                          /* Redirect visitor to the thank you page */

                                          header('Location: thanks.htm');

                                          exit();

                                          /* Functions we used */

                                          function check_input($data, $problem='')

                                          {

                                              $data = trim($data);

                                              $data = stripslashes($data);

                                              $data = htmlspecialchars($data);

                                              if ($problem && strlen($data) == 0)

                                              {

                                                  show_error($problem);

                                              }

                                              return $data;

                                          }

                                          function show_error($myError)

                                          {

                                          ?>

                                              <html>

                                              <body>

                                              <b>Please correct the following error:</b><br />

                                              <?php echo $myError; ?>

                                              </body>

                                              </html>

                                          <?php

                                          exit();

                                          }

                                          ?>

                                           

                                           

                                          I appreciate all the suggestions but am beginning to think I am unsuitable to deal with php!

                                          • 18. Re: error says: Warning: Cannot modify header information
                                            David_Powers Adobe Community Professional (Moderator)

                                            The solution is very simple: all of the HTML markup must be removed before the opening PHP tag. Reorganize your code like this:

                                             

                                            <?php

                                            /* Set e-mail recipient */

                                            $myemail  = "jcoe@bigpond.net.au";

                                            /* Check all form inputs using check_input function */

                                            $yourname = check_input($_POST['yourname'], "Enter your name");

                                            $subject  = check_input($_POST['subject'], "Write a subject");

                                            $email    = check_input($_POST['email']);

                                            $website  = check_input($_POST['website']);

                                            $likeit  = check_input($_POST['likeit']);

                                            $how_find = check_input($_POST['how']);

                                            $comments = check_input($_POST['comments'], "Write your comments");

                                            /* If e-mail is not valid show error message */

                                            if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/", $email))

                                            {

                                                show_error("E-mail address not valid");

                                            }

                                            /* If URL is not valid set $website to empty */

                                            if (!preg_match("/^(https?:\/\/+[\w\-]+\.[\w\-]+)/i", $website))

                                            {

                                                $website = '';

                                            }

                                            /* Let's prepare the message for the e-mail */

                                            $message = "Hello!

                                            Your contact form has been submitted by:

                                            Name: $yourname

                                            E-mail: $email

                                            URL: $website

                                            Like the website? $likeit

                                            How did he/she find it? $how_find

                                            Comments:

                                            $comments

                                            End of message

                                            ";

                                            /* Send the message using mail() function */

                                            mail($myemail, $subject, $message);

                                            /* Redirect visitor to the thank you page */

                                            header('Location: thanks.htm');

                                            exit();

                                            /* Functions we used */

                                            function check_input($data, $problem='')

                                            {

                                                $data = trim($data);

                                                $data = stripslashes($data);

                                                $data = htmlspecialchars($data);

                                                if ($problem && strlen($data) == 0)

                                                {

                                                 $myError = $problem;

                                                }

                                                return $data;

                                            }

                                            ?>

                                            <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

                                            <html xmlns="http://www.w3.org/1999/xhtml">

                                            <head>

                                            <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

                                            <title>Error</title>

                                            </head>

                                            <body>

                                                <b>Please correct the following error:</b><br />

                                                <?php echo $myError; ?>

                                            </body>

                                            </html>

                                            • 19. Re: error says: Warning: Cannot modify header information
                                              BenPleysier Adobe Community Professional & MVP

                                              The solution is to not send headers once an output has been encountered. I have had instances where an output could not be overcome.

                                               

                                              What is wrong with reply #5

                                              echo "<script>location.href = 'thanks.htm'</script>";
                                              • 20. Re: error says: Warning: Cannot modify header information
                                                Level 4

                                                BenPleysier wrote:

                                                 

                                                The solution is to not send headers once an output has been encountered. I have had instances where an output could not be overcome.

                                                 

                                                What is wrong with reply #5

                                                echo "<script>location.href = 'thanks.htm'</script>";

                                                It has already been stated that a user may have javascript disabled. A noscript meta refresh fallback would be less "unprofessional". It should go without saying that javascript/meta redirect methods are generally discouraged in a PHP script because if not for any other reason it's thought of as a cop out when you can't (or don't want to bother to) identify what the real issue is with headers already being sent. Output can always be overcome with refactoring. Choosing not to refactor your code to alleviate header output errors and instead using something like a javascript/meta redirect is just outright lazy.

                                                 

                                                best,

                                                Shocker

                                                • 21. Re: error says: Warning: Cannot modify header information
                                                  Susan_at_Akuaba Level 1

                                                  This absolutely worked.  Thank you for all your efforts!

                                                  • 22. Re: error says: Warning: Cannot modify header information
                                                    BenPleysier Adobe Community Professional & MVP

                                                    No JavaScript? I dare you to turn JavaScript off for one week!

                                                     

                                                    An other lazy, but PHP-geek accepted solution is to use output buffering.

                                                    • 23. Re: error says: Warning: Cannot modify header information
                                                      David_Powers Adobe Community Professional (Moderator)

                                                      I wouldn't call the use of output buffering functions lazy. There can be legitimate reasons to redirect after output has been sent to the browser, for example if an include file can't be found.

                                                       

                                                      <?php ob_start(); ?>

                                                      Lots of content here

                                                      <?php

                                                      if (file_exists('really_important.php')) {

                                                         require 'really_important.php;

                                                         // output the buffer contents

                                                         ob_end_flush();

                                                      } else {

                                                         // clear the buffer

                                                         ob_end_clean();

                                                         header('Location: error.php');

                                                         exit;

                                                      }

                                                      ?>

                                                      1 person found this helpful
                                                      • 24. Re: error says: Warning: Cannot modify header information
                                                        osgood_ Level 8

                                                        BenPleysier wrote:

                                                         

                                                        No JavaScript? I dare you to turn JavaScript off for one week!

                                                         

                                                         

                                                        I would class your solution as perfectly legitimate given most websites now heavily rely on javascript. Maybe that wasn't the case a few years back. Do I care about those still using IE8, no. Do I care about those with js turned off - definitely not.

                                                         

                                                        Yes, IF, as is the case here a more 'logical' reason for something not working can be found and addressed then it's best to use that solution but I don't think I'll  be frowning or losing any sleep if I had to use the js option.