From 43b88d90775ab9a4d2e24df4b4cffb226ef6766b Mon Sep 17 00:00:00 2001
From: Olav Morken <olav.morken@uninett.no>
Date: Wed, 24 Feb 2010 09:52:55 +0000
Subject: [PATCH] Session: Use transient session if headers are already sent.

git-svn-id: https://simplesamlphp.googlecode.com/svn/trunk@2190 44740490-163a-0410-bde0-09ae8108e29a
---
 lib/SimpleSAML/Session.php              | 9 ++++++++-
 lib/SimpleSAML/SessionHandlerCookie.php | 6 ++++++
 lib/SimpleSAML/SessionHandlerPHP.php    | 5 +++++
 3 files changed, 19 insertions(+), 1 deletion(-)

diff --git a/lib/SimpleSAML/Session.php b/lib/SimpleSAML/Session.php
index a33740ca4..806b028ea 100644
--- a/lib/SimpleSAML/Session.php
+++ b/lib/SimpleSAML/Session.php
@@ -142,7 +142,14 @@ class SimpleSAML_Session {
 		/* Check if we have stored a session stored with the session
 		 * handler.
 		 */
-		self::$instance = self::loadSession();
+		try {
+			self::$instance = self::loadSession();
+		} catch (Exception $e) {
+			/* For some reason, we were unable to initialize this session. Use a transient session instead. */
+			self::useTransientSession();
+			return self::$instance;
+		}
+
 		if(self::$instance !== NULL) {
 			return self::$instance;
 		}
diff --git a/lib/SimpleSAML/SessionHandlerCookie.php b/lib/SimpleSAML/SessionHandlerCookie.php
index 0ced9a384..040483a7e 100644
--- a/lib/SimpleSAML/SessionHandlerCookie.php
+++ b/lib/SimpleSAML/SessionHandlerCookie.php
@@ -36,6 +36,12 @@ extends SimpleSAML_SessionHandler {
 			$this->session_id = $_COOKIE['SimpleSAMLSessionID'];
 		}
 
+		/* We need to create a new session. */
+
+		if (headers_sent()) {
+			throw new SimpleSAML_Error_Exception('Cannot create new session - headers already sent.');
+		}
+
 		/* Check if we have a valid session id. */
 		if(self::isValidSessionID($this->session_id)) {
 			/* We are done now if it was valid. */
diff --git a/lib/SimpleSAML/SessionHandlerPHP.php b/lib/SimpleSAML/SessionHandlerPHP.php
index b404c82ca..5d1b05315 100644
--- a/lib/SimpleSAML/SessionHandlerPHP.php
+++ b/lib/SimpleSAML/SessionHandlerPHP.php
@@ -46,6 +46,11 @@ class SimpleSAML_SessionHandlerPHP extends SimpleSAML_SessionHandler {
 			}
 
 			if(!array_key_exists(session_name(), $_COOKIE)) {
+
+				if (headers_sent()) {
+					throw new SimpleSAML_Error_Exception('Cannot create new session - headers already sent.');
+				}
+
 				/* Session cookie unset - session id not set. Generate new (secure) session id. */
 				session_id(SimpleSAML_Utilities::stringToHex(SimpleSAML_Utilities::generateRandomBytes(16)));
 			}
-- 
GitLab