PHP How to completely destroy a session after leave the page

Tags: , , , ,



I want to make a simple PHP page where you can only access if you log in first. My code is something like this:

if (the user logged in correctly) {

session_start();
  echo "THE HTML PAGE. (I did this in echo because I only want to show it for the logged in users.)";

} else {
    header ("Location: index.html");
    die();
    session_destroy();
}

So my goal is that, when the user click onto the “Go back on page” button, the session gets destroyed, and only start a new after logged in. But now, if the user click onto the “Go back on page” button, than click onto the “Go forward on page” button. it says, Document Exired. It’s cool, but if I refresh the page, I can access the page without login.

Answer

Here is a solution


// put on top of every page
session_start();


function is_logged_in(): bool
{
    if (isset($_SESSION['email']) && isset($_SESSION['id']) && isset($_SESSION['is_logged_in'])) {
        return true;
    } else {
        return false;
    }
}
function is_auth()
{
    if (!is_logged_in()) {  
       session_destroy(); // change happend here
       header("Location: index.html");
       die();
    }
}

is_auth();

//  add your code here


Source: stackoverflow