-1

Is there any better way to redirect because I get this error:

Warning: Cannot modify header information - headers already sent by (output started at C:\xampp\htdocs\falco\index.php:26) in C:\xampp\htdocs\falco\classes\controller.php on line 306

Very often by using header("Location: blablabla.php?id=3") Is there any other way to redirect and not get this error? or maybe I am doing something wrong?

THANK YOU FOR YOUR TIME.

TooCooL
  • 20,356
  • 6
  • 30
  • 49

5 Answers5

2

You have to do header changes before any content on your page (also whitespace I think). So place the header function at the very top of your page.

Midas
  • 7,012
  • 5
  • 34
  • 52
2

You must have some whitespace or other output before you call header() which is triggering this warning. See the manual:

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.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
AJ.
  • 27,586
  • 18
  • 84
  • 94
2

This is a warning, not an error. It occurs because the headers were already sent to the browser. Make sure, that you don't have any output in your PHP file before modifying the header. This includes echo, print_r and also whitespaces before your intial <?php tag.

Alp
  • 29,274
  • 27
  • 120
  • 198
2

Headers need to appear before the body of your response. Therefore, if you have anything echo'd (including whitespace) and then attempt to send a header, it will fail.

Leave output for the very last thing in PHP.

alex
  • 479,566
  • 201
  • 878
  • 984
2

You are printing headers after you've printed something else. The first method is just what you're doing, but you will have to wait with printing anything else until you know whether you want to redirect or not. You can use the output buffering functions if you absolutely must print before that. ob_start at the beginning to "pause" printing, then print the header, then call ob_end_flush to print everything that was held back.

Second method is inserting this into the <head>, but this too is timing-specific - you can't just insert it anywhere in the document.

<meta http-equiv="refresh" content="0; url=http://www.example.com/"/>

Third method, stick this script anywhere - but this forces the client to have scripts allowed, or nothing happens:

<script> location.replace('http://example.com'); </script>
Amadan
  • 191,408
  • 23
  • 240
  • 301