2

I am working with PHP and I got this message

cannot modify header information - headers already sent by (output started at

after executing a code which looks like this:

<?php
    if (condition) {

        if (condition) {
            //Statement
        }

        $to = $_POST['email'];
        $subject = "Registration Confirmation";

        $message = '
                <html>
                    <head>
                        <title>'.$subject.'</title>
                    </head>
                </html>
            ';

        // Always set content-type when sending HTML email
        $headers = "MIME-Version: 1.0" . "\r\n";
        $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";

        // More headers
        $headers .= 'From: <contact@ghanalifestore.com>' . "\r\n";

        mail($to,$subject,$message,$headers);

        header('Location: reset.php?username='.$username);
        exit();

    }else {
        //statement
    }

Based on this answer from Stackoverflow, I think the error is coming from the HTML code in the variable $message. I don't really know how I can modify the content of that variable to avoid the error.

Kindly help me solve this problem.

Community
  • 1
  • 1
Prince
  • 1,190
  • 3
  • 13
  • 25

5 Answers5

10

ob_start();

html is also sending output that is why this is happening so use ob_start(); in top of your code, hope this solves your problem.

Anay Pareek
  • 121
  • 1
  • 8
8

From php documentation:

Remember that header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP.

So move header('Location: reset.php?username='.$username); before any other kind of output.

By the way, this question was already answered:

Community
  • 1
  • 1
Sylter
  • 1,622
  • 13
  • 26
  • thanks for answering, is it possible to put the header after the second `if condition` and place `exit()` after the function `mail()` ? – Prince Jun 25 '16 at 11:48
  • 1
    Sure. Be sure that *nothing* before `header()` outputs something. So no HTML, no error message, nothing has to be printed before `header()`. Is the one that you posted the full code of the page? If you have any trouble, post the full code. – Sylter Jun 25 '16 at 11:50
  • Thanks, everything is ok now. – Prince Jun 25 '16 at 12:05
0

just change your code to echo'window.location="dashboard.php?id=40";'; then it will work

0

change your code:-
echo'window.location="username='.$username";';
exit();

0

I pulled my hair out trying to find this issue in PHP code only to find that clearing the cache (Firefox) removed the error. If you are changing code, copying files, etc. your browser could get very confused so whenever you have an error like this or any error that involves how the code is read and you are observing irregularities on the screen or confusing log errors be sure to clear the cache and restart your browser as a possible remedy.