-3

Possible Duplicate:
Headers already sent by PHP

I've been using the header("Location: ..") command everwhere in my PHP files. Usually, I would run several checks (if / else) and then simply redirect the user if all the info is correct or send them somewhere else if it isn't.

Header has been used even after I echoed and in between html tags. Everything worked. I never knew there were limitations anyway, I thought I can use it everywhere..

Today I fiddled around a bit with the header tags and suddenly those warning messages kept popping up in my log files and things stopped working.

So I have two questions:

1) What is the correct approach to serving the correct views? Should I rather conditionally include PHP HTML code in the same file?

2) Why does it work in some cases? For example I have my logginIn() function which is called AFTER html and input fields etc have already been shown.. yet it works.

Community
  • 1
  • 1
Frank Vilea
  • 8,323
  • 20
  • 65
  • 86
  • 5
    This is [a very common question](http://stackoverflow.com/search?q=Cannot+modify+header+information) and the answers are the same every time. – feeela Sep 20 '11 at 22:38

3 Answers3

1

1) Check everything you need before actually outputting your code, or use manual output buffering

<?php
ob_start();
echo "hello";
ob_end_flush();
header("Location:http://stackoverflow.com"); // redirects you

or even worse solution, turn on output_buffering (php.ini).

2) So you've probably got output_buffering turned on

genesis
  • 50,477
  • 20
  • 96
  • 125
  • I would always use manual output buffering. It gives you more control over your code and makes life easier when you can't always guarantee ini settings – adlawson Sep 20 '11 at 22:41
1

Try using output buffering.

A quick example:

<?php
ob_start();

// ... some more code ...
header("Location: www.google.com");

echo 'something';

ob_end_flush();
Daveo
  • 1,155
  • 2
  • 8
  • 16
1

I have written a complete solution to this problem at http://digitalpbk.com/php/warning-cannot-modify-header-information-headers-already-sent. Hope it addresses everyones issues with headers and cookies.

digitalPBK
  • 2,859
  • 25
  • 26