1: 2: 3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: 14: 15: 16: 17: 18: 19: 20: 21: 22: 23: 24: 25: 26: 27: 28: 29: 30: 31: 32: 33: 34: 35: 36: 37: 38: 39: 40: 41: 42: 43: 44: 45: 46: 47: 48: 49: 50: 51: 52: 53: 54: 55: 56: 57: 58: 59: 60: 61: 62: 63: 64: 65: 66: 67: 68: 69: 70: 71: 72: 73: 74: 75: 76: 77: 78: 79: 80: 81: 82: 83: 84: 85: 86: 87: 88: 89: 90: 91: 92: 93: 94: 95: 96: 97: 98: 99: 100: 101: 102: 103: 104: 105: 106: 107: 108: 109: 110: 111: 112: 113: 114: 115: 116: 117: 118: 119: 120: 121:
<?php
namespace MvcCore\Session;
trait Starting
{
public static function Start (& $session = []) {
if (static::GetStarted()) return;
$req = self::$req ?: self::$req = \MvcCore\Application::GetInstance()->GetRequest();
if ($req->IsInternalRequest() === TRUE) return;
static::preventSessionFixation($req);
$sessionStartOptions = [
'cookie_secure' => $req->IsSecure(),
'cookie_httponly' => TRUE,
];
if (PHP_VERSION_ID >= 70300)
$sessionStartOptions['cookie_samesite'] = TRUE;
static::$started = session_start($sessionStartOptions);
static::$sessionStartTime = time();
static::$sessionMaxTime = static::$sessionStartTime;
static::setUpMeta();
static::setUpData();
}
public static function GetSessionStartTime () {
return static::$sessionStartTime;
}
public static function GetStarted () {
if (static::$started === NULL) {
$req = self::$req ?: self::$req = \MvcCore\Application::GetInstance()->GetRequest();
if (!$req->IsCli()) {
$alreadyStarted = session_status() === PHP_SESSION_ACTIVE && session_id() !== '';
if ($alreadyStarted) {
static::$sessionStartTime = time();
static::$sessionMaxTime = static::$sessionStartTime;
static::setUpMeta();
static::setUpData();
}
static::$started = $alreadyStarted;
}
}
return static::$started;
}
protected static function preventSessionFixation (\MvcCore\IRequest $req) {
$sessionCookieName = session_name();
$rawCookieHeader = ';' . trim($req->GetHeader('Cookie', '-,=;a-zA-Z0-9'), ';') . ';';
$sessionCookieNameExtended = ';' . $sessionCookieName . '=';
if (substr_count($rawCookieHeader, $sessionCookieNameExtended) > 1) {
$sentSessionId = '';
$lastPoss = mb_strrpos($rawCookieHeader, $sessionCookieNameExtended);
if ($lastPoss !== FALSE) {
$rawSentSessionId = mb_substr($rawCookieHeader, $lastPoss + mb_strlen($sessionCookieNameExtended));
$valueEndPos = mb_strpos($rawSentSessionId, ';');
if ($valueEndPos === FALSE) {
$sentSessionId = $rawSentSessionId;
} else {
$sentSessionId = mb_substr($rawSentSessionId, 0, $valueEndPos);
}
if (mb_strlen($sentSessionId) > 128)
$sentSessionId = mb_substr($sentSessionId, 0, 128);
$sentSessionId = str_replace('=', '', $sentSessionId);
$_COOKIE[$sessionCookieName] = $sentSessionId;
session_id($sentSessionId);
}
}
}
}