Sujata Hulsurkar
Sujata Hulsurkar

Reputation: 115

Unable to logout user using session_destroy in PHP?

Here is my code included at the top of each page:

<?php 
session_start();
// More Code Here //

Here is my code for login button :

function Login() {
// Connecting to Database  
  if($rows == 1) {
  // Setting a Cookie
  $_SESSION['login'] = true;
  }
mysqli_close($connection);
}

Here is my code for logout button:

function Logout() {
  session_destroy(); 
  return true;
}

I call these functions under conditions like:

if (isset($_POST['submit']) && $_POST['submit'] == 'logout') {
  $bool = Logout();
  if($bool == true) {echo 'Logged Out!'; }
}

but it never echos Logged Out. What am I doing wrong here? This is also the sequence of code in my PHP file. First login function, then logout function and then condition to check which function to call.

This is the HTML form:

<?php if($_SESSION['login']==true) { ?>
  <li>
    <form class="form-inline" method="post" action="">
      <button type="submit" value="logout">Log Out</button>
    </form>
  </li>
<?php } ?>
<?php if(!isset($_SESSION['login'])) { ?>
  <li>
    <form method="post" action="">
      <button type="submit" name="submit" value="login">Login</button>
    </form>
  </li>
<?php } ?>

Upvotes: 0

Views: 290

Answers (1)

Stuart Wagner
Stuart Wagner

Reputation: 2067

You'll need to give your button a name attribute to correspond with the $_POST array:

<button name="submit" type="submit" value="logout" class="btn btn-sm btn-warning" style="margin-left:10px">Log Out</button>

Upvotes: 1

Related Questions