Recommended way to detect sessions
I've created a little class to generate thumbnails with an external program (gm
from ImageMagick, in case you're interested). The class issues an exec()
call to launch gm.exe
but I've hit a PHP bug that makes httpd.exe
freeze when there are concurrent executions and there is an open PHP session. There is a workaround that looks like this:
session_write_close();
exec('gm convert -resize 100x100 source.jpg target.jpg');
session_start();
So far so good. Now I want to reuse the thumbnail class in other present and future projects. If I want to be able to just drop the code and call it without changes, I need to omit the session work开发者_开发问答around when there aren't sessions and I need to do it programmatically. Otherwise, my thumbnailer will have the nasty side effect of starting a session by itself.
How can I properly detect whether there is an active session? Or, in other words, whether the PHP script that is calling my function has issued a call to session_id()
and haven't closed or destroyed the session in any fashion so the operating system is probably holding an open handle that is locking the session file so it cannot be accessed by other running processes which can possibly freeze httpd.exe
.
I've tried this:
if( session_id() ){
session_write_close();
exec('gm convert -resize 100x100 source.jpg target.jpg');
session_start();
}
But I've noticed that session_id()
returns a value if the script ever used sessions, even if they're not active at this point. If the script has closed the session with session_write_close()
... my thumbnailer will open it again!
You cant really. It doesn't look like there are any functions to do that. http://www.php.net/manual/en/book.session.php
You could maybe do some analysis of the files in the directory returned by session_save_path(). But you're going to have issues doing that reliably with different platforms and non-standard session handlers.
The only way I found was to use session_regenerate_id()
, which will return false if there is no active session. But this has the obvious disadvantage that it might break any scripts coming after that rely on the old session id.
There isn't any method within PHP to do this. I ended up having to do a couple simple wrapper functions that check for a global variable (bleah) which my session-start wrapper function set once the session was started the first time.
精彩评论