Forget Me Not: PHP Sessions Should Be Started First

I’m sure I’ll continue to forget this, since this is the third or so time it’s happened to me, but I’m going to leave a note for later anyway. Maybe this will make it more obvious to myself. 🙂

If you’re experiencing weird/broken stuff with your PHP SESSION variables, and if you check the error log and see a message about headers….

Warning: session_start(): Cannot send session cookie – headers already sent by

… then you are starting your session after some kind of output has already been sent to the user. For the visual example, take a look at the following before smacking your forehead. The first example is correct, the second is probably wrong.


session_start();
include ('header.php');

———

include ('header.php');
session_start();

Consider myself reminded. That is all.