2

I have a form on my site that I have included in a sidebar on the page. Basically what it does is collects some data, and if that data has been correctly filled in, it passes it on to a larger form on another page.

The problem is, I keep getting the 'headers already sent' error when it gets submitted. The weird thing is, the form works fine on my development server.

Basically my code looks like this;

    <?php
    if($_SERVER['REQUEST_METHOD'] == 'POST'){

        // Checks for errors are here (omitted for brevity)

        if(!$errors){
            header('Location:'.bloginfo('url').'?page_id=xxx');
        }
    }
    ?>

Bearing in mind that I have to check for errors, is there another way that I can redirect to another page on the site without using header()?

mrbubbles
  • 687
  • 6
  • 19

2 Answers2

2

Any function that sends or modifies HTTP headers must be invoked prior to any output otherwise as you've seen it will fail.

There is a good post/explanation on this at the below link. How to fix "Headers already sent" error in PHP

Community
  • 1
  • 1
llanato
  • 2,508
  • 6
  • 37
  • 59
  • Thanks Atallon. I understand that header() has to be used before any other output now. So would the solution be to make my check for $errors in the header, and then redirect from there? – mrbubbles Mar 21 '13 at 12:19
  • If you can add in the check on $errors before any code is output then it should solve your issue. – llanato Mar 21 '13 at 12:47
2

No problem, you can use the key/values from $_POST to generate the redirect :

<?php
if($_SERVER['REQUEST_METHOD'] == 'POST'){

    // Checks for errors are here (omitted for brevity)

    if(!$errors){
        $xxx = 'valueofxxxhere';
        echo '<script>document.location="'.bloginfo('url').'?page_id='.$xxx.'";</script>';
        die();
    }
}
?>

Not my design by choice (always better to redirect from the headers) but sometimes useful.

darma
  • 4,687
  • 1
  • 24
  • 25
  • Thanks for the answer Darma, although like you I would prefer to do it using header(), so I'm going to try and do it in the header before any output. – mrbubbles Mar 21 '13 at 12:46