Exactly when and where should I use session_start() in PHP?
For example, say I have a login script that sets a session variable to tell whether or not t
As others have said, the absolute requirements of what you must do are:
session_start before you read or write to $_SESSION (otherwise it will just be an ordinary array and not saved anywhere).session_start twice during a single script execution (page load) unless you use session_write_close to close it in between.There is an extra rule that technically has exceptions, but is best treated as absolute:
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:
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".