-2

When you try to redirect an user with Header:Location to another page when there is already 'output' on the page, PHP will display the message: headers already sent.

Is it a good solution to create a function, and call that function wherever you need it (even at the bottom of the page)?

Thanks!

Example:

function redirectMe($location){
    header('Location:'.$location);
}

//HTML

//Redirect user:
redirectMe('http://www.google.com');
Jordy
  • 4,719
  • 11
  • 47
  • 81

3 Answers3

2

No, that won't work because you have already output HTML by the point that the function is called.

If you want to use a redirect, it has to be before ANYTHING is output to the user. Check the variables before you output anything, the either do so and that's it, or decide not to redirect the user - then output all your HTML.

Edit: In an utterly horrible way though, if you can't work out how to check the conditions to redirect/stay, you could possibly put all your HTML into a string, then at the end of the page echo it out - but lordy, doing that would be much more work than checking the correct conditions and going from there.

Fluffeh
  • 33,228
  • 16
  • 67
  • 80
2

A good solution would be to use ob_start() and ob_end_clean()

ob_start();
// all your PHP/HTML codes go there.
$output = ob_get_contents();
ob_end_clean();

more http://php.net/manual/en/function.ob-start.php

samayo
  • 16,163
  • 12
  • 91
  • 106
2

If anything is getting outputted to the browser before the execution of the header function for redirecting, it will give headers already sent error. If no output is needed to be shown to user, you can use ob_start() function at the start of your page to buffer the output beofre being sent to the browser and use ob_flush after the header. You can use it according to the flow of your page

rakeshjain
  • 1,791
  • 11
  • 11