on every page (first lines, first code) I have those two lines of code:
define("DIRECT_ACCESS", true); defined("DIRECT_ACCESS") OR die(header("Location: https://website.com/"));
after those two lines of code, I always do session_start();, I read that session_start() should come as a first thing, before anything. Session_status() shows that session is active and working properly, so I have a couple of questions:
1. Why does the session work if it should be the first line, before other code?
2. Is there anything dangerous that can happen, could something stop working later if I don’t put session_start() as the first line of code?
Thanks for your time trying to help me.
Advertisement
Answer
I read that
session_start()
should come as a first thing, before anything.
That statement is basically wrong.
There’re a few things to take into account when initialising sessions:
With the default (and recommended) settings, session ID is transmitted through a cookie. Server-side cookies are set through HTTP headers. HTTP headers need to be sent before response body. Thus you need to avoid constructs like this:
echo 'Hello, World!'; session_start();
You cannot use session data before it’s retrieved from the persistent storage. That’s precisely what
session_start()
does. So you cannot do this:$user_name = $_SESSION['user_name']; session_start();
Some times you may want to close the session in order to unlock the storage. You do that with
session_write_close()
. Once you do that, session data remains loaded but changes won’t persist. So please avoid:session_write_close(); $_SESSION['user_name'] = 'john.doe';
Other than that, you’re free to start sessions whenever you see fit.