Handling Cookies: Deleting and Setting During the Same Session
This article focuses on the methodology of firstly deleting and then setting a cookie during the same session. Following this procedure will yield the desired results. It is assumed that you have prior knowledge with setting and deleting cookies. Our scripting language of choice is PHP. You can read more about setting cookies with PHP by referring to its manual.
The issue arising here is that the browser session has to be restarted if a cookie is deleted, and then an attempt is made to set it again during the same session, given that it does not exist. This is due to browsers keeping session cookies in memory.
The objective:
Start a session. Do a check A. If check A is true, delete cookie X bearing value Y. Do some more operations. It is time for the cookie again. Do a check C, where check C checks if cookie X is set . If check C is not true, set cookie X with value Z.
The problem:
Check A was true, cookie X with value Y was deleted, but check C returns true and creation of cookie X with value Z does not happen. This is true for all major browsers as they keep the received cookies for a session in memory hence deleting them does not remove them from browsers memory. The result is: when check C is performed the cookie X with value Y is still in memory, despite the fact that it was “physically” deleted, hence it returns true. Consequently the website functionality is handicapped as cookie X still has value Y but value Z is needed.
The solution:
Start a session. Do a check A. If check A is true, delete cookie X bearing value Y. Set a check B to true (this keeps track that the cookie deletion occurred). Do some more operations. It is time for the cookie again. If check B is true set cookie X with value Z, else do check C, where check C checks if cookie X is set . If check C is not true, set cookie X with value Z.
The latter introduced check B forces the creation of the cookie X with value Z, thus, overriding the one in memory with value Y. Hence, the website functionality is as it was intended, without the session having to be restarted.

, or by using our


