Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can you delete a cookie in an HTTP response?

Tags:

http

cookies

What is the preferred way to instruct a browser to delete (or no longer use) an HTTP cookie issued for a given domain in an HTTP response?

(I understand you cannot force the browser to delete the cookie, but there must be a way to indicate that it is no longer valid and should not longer be sent)

like image 375
Mike Avatar asked Dec 02 '13 03:12

Mike


People also ask

Which method is used to delete a cookie?

Deleting Cookie: There is no special dedicated function provided in PHP to delete a cookie. All we have to do is to update the expire-time value of the cookie by setting it to a past time using the setcookie() function. A very simple way of doing this is to deduct a few seconds from the current time.

How you can delete a cookie in ASP NET?

Add(new HttpCookie("ASP. NET_SessionId", "")); This code example clears the session state from the server and sets the session state cookie to null. The null value effectively clears the cookie from the browser.


2 Answers

Just set the cookie on exactly the same name, path and domain, but with an Expires value in the past. Optionally, set the value to null/empty-string, even if it's just to save the bandwidth, it's otherwise ignored anyway by the average client.

Note that setting on exactly the same path is important. Many starters fail in this by using only the same name and domain and relying on the current request URL for the default path.

From the RFC6265 spec:

Finally, to remove a cookie, the server returns a Set-Cookie header with an expiration date in the past. The server will be successful in removing the cookie only if the Path and the Domain attribute in the Set-Cookie header match the values used when the cookie was created.

Using Max-Age=0 will also work with any spec-compliant user agent, but the spec dictates that a server "SHOULD" not do this. Per https://www.rfc-editor.org/errata/eid3430, this is apparently meant to maximise interoperability with non-compliant user agents that only support positive Max-Age values.

like image 64
BalusC Avatar answered Sep 19 '22 09:09

BalusC


You may set the time to 0 or anytime that has expired.

In PHP only you may use the following, but for your scenario you may only take from this the fact that the time is being manipulated

// Use the following for immediate elimination for current running server script unset($_COOKIE['cookiename']);   // In order to eliminate all together which involves notifying client-side. Expire time setcookie('cookiename', '', time() - 3600); 
like image 38
Johnny Harlamert Avatar answered Sep 20 '22 09:09

Johnny Harlamert