Reopening a session in PHP

后端 未结 2 1371
萌比男神i
萌比男神i 2020-12-03 07:54

How do I reopen a session in PHP without getting header already sent warnings?

After setting all the session vars I like to set, I close the session with session_wri

相关标签:
2条回答
  • 2020-12-03 08:15
    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
    
    0 讨论(0)
  • 2020-12-03 08:17

    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

    0 讨论(0)
提交回复
热议问题