Skip to content
Advertisement

session_start() prevents saving in WordPress editor

I have the following code in my custom WordPress plugin:

add_action('init', 'wwp_StartSession', 1);

function wwp_StartSession() {
    if(!session_id()) {
       session_start();
    }
}

When I edit this in the WordPress editor it can be saved. However if I want to save again after more edits I get the following error:

Unable to communicate back with site to check for fatal errors, so the PHP change was reverted. You will need to upload your PHP file change by some other means, such as by using SFTP.

When I remove the line

sesion_start();

I am able to save again.

I already Googled for quite a while now and some say that the if(!session_id()) should do the trick, but it seems it doesn’t.

Hoping someone has any ideas on this.

Advertisement

Answer

Finally I found out :). I found the answer here: https://core.trac.wordpress.org/ticket/47320

This is now my code:

class Session {
    public static function startSession() {
         // This loads variables to $_SESSION for reading
         if(!session_id()) {
            session_start();
            session_write_close(); // Other plugins can restart a session again via session_start()
        }
    }

    public static function endSession() {
        session_destroy ();
    }

    public static function storeData($key, $value) {
        session_start();
    
        $_SESSION[$key] = $value;
    
        session_write_close();
    }
}

startSession is hooked to init endSession is hooked to wp_login and wp_logout and wherever I need to save data call storeData

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement