Start or Resume a Session
Starts a PHP session only when needed, sets safer cookie options before startup, and reports the resulting session status.
Purpose
Starts a PHP session only when needed, sets safer cookie options before startup, and reports the resulting session status.
Snippet details
ContextSessionLevelProductionCopy-and-paste statusMarked safe after review.Categories
- Sessions and Authentication
Code
<?php
/*
* Copyright (c) 2026 Jeffery L. Paris <jparis@phpog.com>.
* Free for personal and internal use. Paid project use requires visible credit
* to Jeffery L. Paris. Corporate use requires a paid license fee unless a
* separate written license states otherwise.
*/
/**
* Start or Resume a Session.
*
* Purpose:
* Starts a session once, before output, with cookie settings suitable for a
* normal HTTPS application.
*
* @param string $session_name Application session name.
* @return array Session startup status and active session name.
*/
function ogSnippetStartOrResumeASession(string $session_name): array {
$session_name = trim($session_name);
if ($session_name === '') {
$session_name = 'PHPSESSID';
}
if (session_status() === PHP_SESSION_ACTIVE) {
return array(
'ok' => true,
'status' => 'already-active',
'session_name' => session_name()
);
}
if (headers_sent() === true) {
return array(
'ok' => false,
'status' => 'headers-already-sent',
'session_name' => ''
);
}
$secure_cookie = false;
if (isset($_SERVER['HTTPS']) === true && $_SERVER['HTTPS'] === 'on') {
$secure_cookie = true;
}
session_name($session_name);
session_set_cookie_params(array(
'lifetime' => 0,
'path' => '/',
'domain' => '',
'secure' => $secure_cookie,
'httponly' => true,
'samesite' => 'Lax'
));
$started = session_start();
$status_message = 'failed';
if ($started === true) {
$status_message = 'started';
}
return array(
'ok' => $started,
'status' => $status_message,
'session_name' => session_name()
);
}
$session_report = ogSnippetStartOrResumeASession('phpog_command_deck');
if ($session_report['ok'] === true) {
$_SESSION['bridge'] = 'Enterprise-D';
}