Delete cookie by name?
You should define the path on which the cookie exists to ensure that you are deleting the correct cookie.
function set_cookie(name, value) {
document.cookie = name +'='+ value +'; Path=/;';
}
function delete_cookie(name) {
document.cookie = name +'=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;';
}
If you don't specify the path, the browser will set a cookie relative to the page you are currently on, so if you delete the cookie while on a different page, the other cookie continues its existence.
Edit based on @Evan Morrison's comment.
Be aware that in some cases to identify the correct cookie, the Domain
parameter is required.
Usually it's defined as Domain=.yourdomain.example
.
Placing a dot in front of your domain name means that this cookie may exist on any sub-domain (www
also counts as sub-domain).
Also, as mentioned in @RobertT's answer, HttpOnly
cookies cannot be deleted with JavaScript on the client side.
How to delete a cookie if I only know its name's first few characters - with Javascript?
You could just remove the cookie value using:
function removeCookieValue(name) {
document.cookie = name+'="";-1; path=/';
}
removeCookieValue('_ga')
Clearing all cookies with JavaScript
function deleteAllCookies() {
var cookies = document.cookie.split(";");
for (var i = 0; i < cookies.length; i++) {
var cookie = cookies[i];
var eqPos = cookie.indexOf("=");
var name = eqPos > -1 ? cookie.substr(0, eqPos) : cookie;
document.cookie = name + "=;expires=Thu, 01 Jan 1970 00:00:00 GMT";
}
}
Note that this code has two limitations:
- It will not delete cookies with
HttpOnly
flag set, as theHttpOnly
flag disables Javascript's access to the cookie. - It will not delete cookies that have been set with a
Path
value. (This is despite the fact that those cookies will appear indocument.cookie
, but you can't delete it without specifying the samePath
value with which it was set.)
Remove a cookie
You May Try this
if (isset($_COOKIE['remember_user'])) {
unset($_COOKIE['remember_user']);
setcookie('remember_user', null, -1, '/');
return true;
} else {
return false;
}
Related Topics
How to Get the Index of an Object by Its Property in JavaScript
Track Event in Google Analytics Upon Clicking Form Submit
How to Save JSON to Local Text File
How to Send Variables from One File to Another in JavaScript
Create a String of Variable Length, Filled with a Repeated Character
How to Abort Image <Img> Load Requests Without Using Window.Stop()
How to Submit 2 Forms in One Page with a Single Submit Button
How to Disable Div Element and Everything Inside
How to Retrieve If the Popstate Event Comes from Back or Forward Actions with the HTML5 Pushstate
Origin <Origin> Is Not Allowed by Access-Control-Allow-Origin
Detecting Back Button/Hash Change in Url
How to Check If Page Exists Using JavaScript
Password Encryption at Client Side
How to Append a Div Inside an Svg Element
Prevent Orientation Change in iOS Safari