Reopening a session in PHP
session_start();
...
session_write_close();
...
ini_set('session.use_only_cookies', false);
ini_set('session.use_cookies', false);
ini_set('session.use_trans_sid', false);
ini_set('session.cache_limiter', null);
session_start(); // second session_start
This will prevent php from calling php_session_send_cookie()
a second time.
See it working.
Though restructuring the scripts still seems to be the better option...
For PHP 7.2+, you will basically need to re-implement session cookies to avoid errors and warnings:
ini_set('session.use_only_cookies', false);
ini_set('session.use_cookies', false);
ini_set('session.use_trans_sid', false);
ini_set('session.cache_limiter', null);
if(array_key_exists('PHPSESSID', $_COOKIE))
session_id($_COOKIE['PHPSESSID']);
else {
session_start();
setcookie('PHPSESSID', session_id());
session_write_close();
}
session_start();
...
session_write_close();
...
session_start(); // second session_start
EDIT See @VolkerK's solution, it is better than this one.
Just buffer the output of your script while it executes to prevent the headers from being sent, and output it at the very end:
<?php
session_start();
// setting all the session vars I like to set
session_write_close();
// Start output buffer
ob_start();
// Code that takes some time to execute
// Do session stuff at the end of the script
session_start();
$_SESSION['key'] = 'new value I like to store';
session_write_close();
// Send output to client
ob_end_flush();
Ref: Output control functions