diff --git a/lib/SimpleSAML/SessionHandlerPHP.php b/lib/SimpleSAML/SessionHandlerPHP.php
index 1e9d7850e7d252dff3eb551bffcf67738cbe24fb..b83b6bffadca59fdc94a4d3ac5e5734e52197ca0 100644
--- a/lib/SimpleSAML/SessionHandlerPHP.php
+++ b/lib/SimpleSAML/SessionHandlerPHP.php
@@ -343,6 +343,11 @@ class SessionHandlerPHP extends SessionHandler
             );
         }
 
+        if (session_id() !== '') {
+            // session already started, close it
+            session_write_close();
+        }
+
         session_set_cookie_params(
             $cookieParams['lifetime'],
             $cookieParams['path'],
@@ -351,11 +356,6 @@ class SessionHandlerPHP extends SessionHandler
             $cookieParams['httponly']
         );
 
-        if (session_id() !== '') {
-            // session already started, close it
-            session_write_close();
-        }
-
         session_id($sessionID);
         $this->sessionStart();
     }