I have the following in my PHP header from an existing little web app. My question is: doesn't this make the page jump through an extra step to first check and then start a session? What is the point of this?
If a session exists, can't I just use session_start
and if it does not won't it be ignored?
PHP
if (!isset($_SESSION)) {
session_start();
}
If you call session_start() and no session exists it will create a new session. If there is an existing session it will resume that.
If I'm not mistaken, the $_SESSION
superglobal will always exist, so your code won't really do very much anyway.
If you're on PHP <5.4, use the following code instead:
if (session_id() == "") {
session_start();
}
On PHP 5.4+, use this:
if(session_status() != PHP_SESSION_ACTIVE) {
session_start();
}
You should only really be calling session_start()
once, but as @ScottHelme said, calling it multiple times will not have a negative effect, the session will be either created or resumed every time.