Search code examples
phpphp-8.1

session_write_close() raises "TypeError: Session callback must have a return value of type bool, int returned" error in PHP 8.1


I'm testing PHP 8.1.9 and when I try calling

session_write_close();

It gave me a TypeError: Session callback must have a return value of type bool, int returned error.

Maybe that one relates with this line in php-src/ext/session/mod_user.c

Now I don't know how to fix this on my end.


Solution

  • Thank you @IMSop. You saved my day!

    After searching in the code, we are using session_set_save_handler() like this

    session_set_save_handler(
        array(&$my_custom_session, 'open'),
        array(&$my_custom_session, 'close'),
        array(&$my_custom_session, 'read'),
        array(&$my_custom_session, 'write'),
        array(&$my_custom_session, 'destroy'),
        array(&$my_custom_session, 'gc')
    );
    

    And in MyCustomSession, the write function returns int|boolean based on file_put_contents

    /**
     * @param string $id
     * @param mixed $data
     * @return int|boolean
     */
    public function write($id, $data)
    {
        $my_custom_session_file_path = self::SESSION_PREFIX_PATH . $id;
        return file_put_contents($my_custom_session_file_path, $data);
    }
    

    After forcing write() funtion to return a boolean value, it's OK now.

    /**
     * @param string $id
     * @param mixed $data
     * @return boolean
     */
    public function write($id, $data)
    {
        $my_custom_session_file_path = self::SESSION_PREFIX_PATH . $id;
        return file_put_contents($my_custom_session_file_path, $data) ? true : false;
    }