tags:

views:

31

answers:

1

I am developing a web-based user interface that plots some data from a database and displays it to the user. There are, literally, millions of different graphs that may be generated, so my idea is to dynamically generate the graph, save it to a temporary file, serve the web page and finally remove the image after a certain period of time.

What I would like to do, thus, is to store the paths to the already generated images in $_SESSION so that the files can be deleted when the session is destroyed. Is there a way in PHP to execute a given function (which in this case would be in charge of deleting the aforementioned files) when the session is destroyed, whenever that happens?

+5  A: 

Yes, see session_set_save_handler, in particular the $destroy and $gc parameters.

Artefacto
@Pekka "session.gc_divisor coupled with session.gc_probability defines the probability that the gc (garbage collection) process is started on every session initialization. The probability is calculated by using gc_probability/gc_divisor, e.g. 1/100 means there is a 1% chance that the GC process starts on each request. session.gc_divisor defaults to 100." See [here](http://www.php.net/manual/en/session.configuration.php#ini.session.gc-divisor).
Artefacto
@Artefacto good info, cheers! What context will the garbage collection function run in? Seeing that the original script can have died long ago?
Pekka
@Artefacto: I see that the signature of the function is bool session_set_save_handler (callback $open, callback $close, callback $read, callback $write, callback $destroy, callback $gc). I guess there is no way to just set the destroy handler and garbage colector, isn't?
plok
@Pekka Well, I've just checked the source and every time `session_start` is called it generates a random number and depending on that runs the garbage collector. So it will run in the context of some script in the future.
Artefacto
@plok No, you have to go all the way; provide 6 valid callbacks. See the example on the manual.
Artefacto
@Artefacto interesting. So the garbage collector can't rely on the global state of the rest of the script, it has to be a generic one. Good to know (and not explained in the manual), cheers!
Pekka
@plok as Artefacto says, you have to implement your own session handling if you want to use these callbacks. The manual example is pretty complete, though.
Pekka
@Pekka, @Artefacto: I'm already working on it. Thank you both.
plok