Header("Location: ") is broken

Before today, redirects worked fine. Until today, there is always a warning saying “Headers already sent”.
What I mean is that if for example, there is an invalid ID, I would redirect the user back to the homepage. However, it now displays a warning, breaking the entire code. I tried disabling the error reporting, it didn’t work. I cannot place the header before the HTML since i include() a header.php that contains all the css and all the basic HTML things BEFORE the header().
So it would work like this(simplified):

<?php
    include(header.php);
    $id = $_GET["id"];
    if(validate_id($id)){
        // code logic
    }else{
        header("Location: ../");
    }
?>

Can anyone find a workaround? Any help is greatly appreciated.

Please share the full error message and your full code.

From the information you shared, PHP is outputting something to the user before your code finishes executing (This is somewhat normal, but prevents header manipulation from working)

3 Likes

The “Headers already sent” error usually means your code has already output page content before the header() function is called. This could be caused by code in the header.php file, for example.

One recommendation to help avoid such issues: if you have a file that only contains PHP code, don’t put a closing tag at the end of your code. PHP scripts will work just fine without them. But some editors automatically add a blank line to the bottom of the file. If you have a closing tag, then that blank line will be output to browsers, which will also prevent you from sending more headers later on.

4 Likes