PHP header already sent error, not a whitespace error

This question already has an answer here:

  • How to fix “Headers already sent” error in PHP 11 answers

  • The error is effectively that the second you add any output at all (including whitespace, or in this case, tags), you can no longer call header after that. As a test - comment out your header line temporarily. You'll see that your code works.

    header("Location:/".$group_url."&".$fname_key);

    Will ALWAYS crash your code if you've sent anything else. Comment it out to prove that to yourself. Your code will magically start working again until you uncomment it.

    Most likely, you need to re-engineer your code to either send html ( <div> , <span> , and the like) OR call the header() function, but not both. The other alternative is to move the header call EARLIER in the code, so that it executes WAY before anything else. Then, of course, you'd want to stop execution (since you're asking for a redirect.)

    HOW A BROWSER WORKS

    To understand why this is a problem -- why you can't send a header after sending content (like HTML), think of it how the browser sees the packet:

    HTTP/1.1 200 OK
    Content-Type: text/xml; charset=utf-8
    Content-Length: 28
    
    <div><span>text</span></div>
    

    The header is the first three lines. After that, two carriage returns and then the body. By sending html first, it forces php to calculate headers (including, most importantly, content length!) After that, the headers are sent. You're now on to sending body. So, by calling header() later, to add another header, you're asking php to go back in time and unsend the headers, which of course... it can't do.


    From PHP's own manual (http://php.net/manual/en/function.header.php):

    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. It is a very common error to read code with include, or require, functions, or another file access function, and have spaces or empty lines that are output before header() is called. The same problem exists when using a single PHP/HTML file.

    <html>
    <?php
    /* This will give an error. Note the output
     * above, which is before the header() call */
    header('Location: http://www.example.com/');
    exit;
    ?>
    
    链接地址: http://www.djcxy.com/p/69672.html

    上一篇: 无法理解这个分析问题

    下一篇: PHP头已经发送错误,不是空白错误