As others have said, the absolute requirements of what you must do are:
- You must run
session_start
before you read or write to$_SESSION
(otherwise it will just be an ordinary array and not saved anywhere). - You must not run
session_start
twice during a single script execution (page load) unless you usesession_write_close
to close it in between.
There is an extra rule that technically has exceptions, but is best treated as absolute:
- Do not start the session after you have written any output (
echo
, HTML outside PHP blocks, etc), because PHP may not be able to send cookies to the browser if the server has already started sending the content.
There are two reasons you might want to avoid starting the session:
- PHP locks the session when you open it to avoid two processes writing conflicting data into it, so if you have several requests happening at once, you want to avoid them waiting for each other unless they really need to. For instance, if you’re responding to an AJAX request, and don’t need any data from the session, don’t open it.
- As mentioned by symcbean, there is some cost to creating a new session, so if your site is busy with either legitimate or malicious traffic, you might want to serve some landing pages or error messages without starting it at all.
After that, it becomes a matter of style and architecture, but the rule of thumb that covers most of the above is “as soon as possible, if you’re sure the page needs it”.