Is this PHP conditional statement overly long?
I'm working through a book which creates this function for destroying a session:
function destroy_session_and_data()
{
session_start();
$_SESSION = array();
if (session_id() != "" || isset($_COOKIE[session_name()]))
setcookie(session_name(), '', time() - 2592000, '/');
session_destroy();
}
I was wondering whether the conditional statement is overly long?
Could it not be rewritten as the following:
if (session_id() != "" || isset(session_name()))
That is, doesn't session_name() return the value 'PHPSESSID' without the need for a specific reference to the $_COOKIE array?
Going further, could the conditional not just be written like this:
if (session_id() != "")
Seeing as session_id() returns the VALUE of the key [PHPSESSID] in the $_COOKIE array, if it is not empty then surely it goes without saying that session_name(), which returns the KEY [PHPSESSID], will be set, because they exist together as a name/value pair in the $_COOKIE array?
Cheers for any help!
Answer
Solution:
Since the conditional runs after
session_start
¹, theisset($_COOKIE[session_name()])
check seems redundant to me.What are the circumstances where the session id might be empty and at the same time the
isset
check would be true? The only one I can think of is when session id persistence is not implemented with cookies, but a cookie with the session name has nevertheless been received from the client. In this case clearing the cookie will have no effect because, well, the session doesn't use cookies.So as far as I can tell you can indeed simplify the condition to
¹ If the code ran before
session_start
then theisset
would be able to detect if a session will be continued whensession_start
is later called, although this particular check is simplified and does not handle all cases correctly. In addition, clearing the cookie as a response would not change anything for the current request so while the test itself might theoretically useful, the test + response code as presented is meaningless.