Showing entries with tag "session".

Found 1 entries

PHP: Only start a session when it's needed

I use sessions on my sites for user authentication. Calling session_start() initiates a session and allows me to check if the user is logged in or not. However, calling session_start() creates a new session for every hit on your site: bots, unauthenticated users, etc. This can lead to an excess of session files on your filesystem.

A better way is to explicitly call start_session() when your user logs in. On your other pages you can check if the user has the appropriate session cookie and start a session only when it's needed.

function start_session_if_exists() {
    if (isset($_COOKIE[session_name()]) && session_status() !== PHP_SESSION_ACTIVE) {
        session_start();
    }
}

This will avoid creating a session for every hit on your site.

Leave A Reply