Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does session_register_shutdown actually do?

Tags:

php

From official php manual:

session_register_shutdown — Session shutdown function

Registers session_write_close() as a shutdown function.

So, what does session shutdown mean? What's the difference between session_write_close and this?

To make it clear, what does this function actually do? When shall we use it?

It seems few people are using and talking about this function on the web.

like image 881
Shiji.J Avatar asked Apr 22 '15 23:04

Shiji.J


2 Answers

This function is rarely used actually, there is almost no discussion on the internet, I finally found the answer from the source code comments:

/* This function is registered itself as a shutdown function by
 * session_set_save_handler($obj). The reason we now register another
 * shutdown function is in case the user registered their own shutdown
 * function after calling session_set_save_handler(), which expects
 * the session still to be available.

From: https://github.com/php/php-src/blob/master/ext/session/session.c

And, obviously, compared to the official manual, this clearly states what it exactly do.

This question is just looks silly.

like image 87
Shiji.J Avatar answered Oct 28 '22 14:10

Shiji.J


This is a fair question. I was also confused by the documentation.

What I was able to extract after reading it a dozen times is that the function is just a shortcut version of the code

register_shutdown_function('session_write_close');

If you call die() or exit in a php script the session will not be properly closed (especially if you have a custom session handler). This function is nothing more than a shortcut.

My bootstrap code for my specific session handler looks like:

// Set the session handlers to the custom functions.
$handler = new SQLSrvSessionHandler();
session_set_save_handler(
  array($handler, 'sessionOpen'),
  array($handler, 'sessionClose'),
  array($handler, 'sessionRead'),
  array($handler, 'sessionWrite'),
  array($handler, 'sessionDestroy'),
  array($handler, 'sessionGC')
);
session_register_shutdown();

The function session_register_shutdown insures my function SQLSrvSessionHandler::sessionClose and SQLSrvSessionHandler::sessionWrite are called even if I run a die or exit statements.

I also found this answer helpful.

like image 39
danielson317 Avatar answered Oct 28 '22 12:10

danielson317