0

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");
}
  • Possible duplicate of [jquery, delete cookies](https://stackoverflow.com/questions/3671659/jquery-delete-cookies) – Milan Chheda Aug 13 '17 at 10:06
  • 4
    Do _not_ store the users password in a cookie. That's a _huge_ security issue. You can read this post for an idea on how to make it more secure (using specific generated auth tokens): https://stackoverflow.com/questions/36796205/php-persistent-login-regenerate-login-token – M. Eriksson Aug 13 '17 at 10:07
  • cookies are readable on the user's machine. As already mentioned, don't store the password in one. A conventional session cookie would be more appropriate. – ADyson Aug 13 '17 at 10:09
  • Btw, all the PHP-code in your "logout"-button will always be executed straight away. PHP get's executed on the server. The result will then be sent to the client, which parses and executes any JS. Please read: [What is the difference between client-side and server-side programming?](https://stackoverflow.com/questions/13840429/what-is-the-difference-between-client-side-and-server-side-programming) – M. Eriksson Aug 13 '17 at 10:12
  • PHP is run on the server. jQuery is run on the browser. The two can never meet in this way. You could probably just have a `logout.php` file that deletes the cookies and redirects back to `index.php`. – Niet the Dark Absol Aug 13 '17 at 10:12

3 Answers3

3

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, '/');
Mikkel G
  • 35
  • 6
1

Try:

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

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();

Thomas Gak-Deluen
  • 2,759
  • 2
  • 28
  • 38