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 = array();
if (session_id() != "" || isset($_COOKIE[session_name()]))
    setcookie(session_name(), '', time() - 2592000, '/');

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!




Since the conditional runs aftersession_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 theisset 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 (session_id() != "")

¹ If the code ran beforesession_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.

People are also looking for solutions to the problem: Cannot modify header information - headers already sent by Php ERROR


Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.