简体   繁体   中英

Delete cookie php

I am trying to make a platform with a login system and I am storing the username and the password in cookies to make the user stay logged in even if it closes the browser and then enters again. I managed to save the cookies but I don't know how to make the logout button. Here is the code:

function logout() {
  $('body').append("<?php setcookie('username', null); setcookie('password', null); unset $_COOKIE['username']; unset $_COOKIE['password']; ?>");
  location.assign("index.php");
}

You are trying to include PHP code in JavaScript, which will not work like that. You could either delete the cookie with jQuery as suggested here :

function logout() {
  $.cookie("username", null, { path: '/' });
  location.assign("index.php");
}

or by calling a PHP file with the following PHP code:

setcookie("username", "", time() - 3600, '/');

尝试:

setcookie('username', null, -1, '/'); setcookie('password', null, -1, '/');

You are trying to execute server code inside client code. That won't work. It'll literally append what's inside the append method.

You need to write a logout.php file and inside it have your server side logic.

Such as

<?php
session_destroy();
setcookie("cookie", "value", 1);

header("Location: index.php");
?>

Set cookie to 1second after epoch instead of 0 so that the cookie expires right away and not at the end of the browser session.

Also note that you shouldn't store the password in the cookie. Rather store the session key in the cookie using session_start();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM