0

I am trying to make a login php, but I need to stay logged in. I firstly used cookies but everybody said that I need to use session cookies. I succeded to save the session variables but now I am working on the logout button, that has an onclick event that toggles a function. It doesn't work. Here is the code: JQuery function -

function logout() {
  $('body').append("<?php session_unset(); session_destroy(); ?>");
  location.assign("index.php");
}

PHP -

<?php
if(!isset($_SESSION["username"]) || !isset($_SESSION["password"])){
echo '<button type="button" name="button" onclick="showRegister();">Register</button>
<button type="button" name="button" onclick="showLogin();">Login</button>';
}else{
echo '<button type="button" name="button">Publica un anunt</button>
<button type="button" name="button" onclick="logout();">Logout</button>';
}
?>
hassan
  • 7,812
  • 2
  • 25
  • 36

1 Answers1

0

When you're doing

function logout() {
  $('body').append("<?php session_unset(); session_destroy(); ?>");
  location.assign("index.php");
}

On javascript - it only includes PHP code to the client-side page, doesn't executes it on server side.

If you need to logout - you need to build page logout.php like

<?php 
  session_unset(); session_destroy(); 
?>

And request it with ajax, like this:

function logout() {
  $.ajax({
    url: 'logout.php',
    success: function(){
      location.assign("index.php");
    }
  });
}

Or you can build logout.php like this:

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

And follow user to it by the link without any ajax, like this:

<a href='logout.php'>Log out</a>
MobDev
  • 1,614
  • 17
  • 17