2

I'm trying to understand how I would implement the post/redirect/get pattern if my handler page where everything is $_POST'd to requires session data (checking if the user is logged in, lets say)

I can't call: header("Location /somenewplace", 303); because I'd get a 'Cannot modify headers' error, as I've already called session_start() to get the session data.

Can someone help me understand this pattern a bit better, should your handler require interacting with session data?

Thank you,

Sisyphus
  • 4,181
  • 1
  • 22
  • 15
barfoon
  • 27,481
  • 26
  • 92
  • 138

4 Answers4

2

There is something wrong in your code. The session_start() shouldn't send the headers. Use PHP output buffering to ensure no output is sent.

Gedrox
  • 3,592
  • 1
  • 21
  • 29
2

A call to session_start() should only modify the headers. You probably outputted some data somewhere else in your script. When PHP gives you the message 'Cannot modify headers' it usually tells you on which line the output was started.

So sessions should not prevent you from doing any redirects or other things.

2

Usually when I get that error its because something has already been outputted to the user. You cannot output any data before calling header(). Check to see if you are printing/echoing anything before header is called. Also check your closing tags on your scripts, if you have a space after a closing tag ?> php will output that to the user and set the headers.

copacetic
  • 414
  • 4
  • 13
  • WOW! This was it. I had a single space character at the bottom of one of my included files and was outputting this. Once I removed it the header() call worked. Thank you! – barfoon Jul 06 '11 at 21:14
  • 1
    A very common practice which is embraced by several coding communities is to always leave out the closing ?> tag. This wont cause any errors or warnings and it will prevent this error in the future – copacetic Jul 07 '11 at 16:17
1

Check out using ob_start() and ob_end_flush() to use output buffering.

kinakuta
  • 9,029
  • 1
  • 39
  • 48