You can only do redirect if nothing has been sent to the browser already. This means you have to do one of two things:
Work out if you need to redirect before you send any data.
Use ob_start
to hold the page until it has finished processing. As soon as you throw a header
call, it will dump the buffered copy and just send the header. But you have to call ob_start
right at the beginning so it catches any output. Its PHP page should give you some clues on this.
My personal preference lies with output buffer (ob) but it will mean no data gets sent to the client until the whole page is done rendering. This can sometimes make the site seem a little slow if the page takes a long time to generate.
You can combat slowness by calling ob_flush
which sends the contents of the buffer to the client. I recommend doing this as soon as you know you won't need to send a header
change. But it's completely optional and not worth the effort for simple and quick scripts.