session_start() prevents saving in Wordpress editor

情到浓时终转凉″ 提交于 2020-07-23 06:43:25

问题


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.


回答1:


It still behaves strange. If I do this:

public function startSession() {
    if(!is_admin() && !session_id()) {
        echo 'not session id';
        session_start();
    } 
}

Then it does save in the backend....however I don't have my session variables available...even though the echo statement is printed, so session_start() is called.

If I leave out the !is_admin() part I can work with the session....but then I have the backend trouble again.




回答2:


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



来源:https://stackoverflow.com/questions/62176291/session-start-prevents-saving-in-wordpress-editor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!