Home > other >  PHP Script keeps logging user out
PHP Script keeps logging user out

Time:02-10

I'm relative new to php and I want users to access my site only with a login. So far so good, that's no problem. Now I want that the user stays logged in, even if he clicks page refresh. This worked well, until I added the followin line to my code:

<a onclick="console.log('<?php session_unset();?>)">Logout</a>

The full site code is:

<?php
        session_name("login_session");
        session_start();
        if(isset($_SESSION["user"])){
            echo "<script>console.log('User logged in');</script>"; //Debugging
        }
        else{
            header('location:index.php');
        }
        
?>

<!DOCTYPE html>
<html>

<head>
    <title>Home</title>
    <link rel="stylesheet" href="css/site.css" />
    <link rel="stylesheet" href="css/gauge.css" />
    <meta charset="utf-8" />
</head>

<body>

    <div id="mySidenav" >
        <a href="javascript:void(0)"  onclick="closeNav()">&times;</a>
        <a href="#">Dashboard 1</a>
        <a href="#">Dashboard 2</a>
        <a onclick="console.log('<?php session_unset();?>')">Logout</a> //There is the problem
    </div>

    <div  id="gc__1">
        MAIN CONTENT
    </div>

    <script src="javascript/sidenav.js"></script>
    <script src="javascript/gaugevalue.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/paho-mqtt/1.0.1/mqttws31.min.js"
        type="text/javascript"></script>
    <script src="javascript/dashboard_mqtt.js"></script>

</body>

</html>

I know, that the Problem must be with this line because I tried to delete it and then it worked well!

Thank you!

CodePudding user response:

You cannot call a PHP function from within JavaScript, the following line:

 <a onclick="console.log('<?php session_unset();?>')">Logout</a>

... is simply calling session_unset when the server is rendering the page. You need to setup a logout route and use the logout link to navigate to that and then you would call session_unset() on that page.

CodePudding user response:

PHP is interpreted on the web server and every PHP template tag will be executed on the webserver, so when you call the "logout" function, it will be executed on the server.

To build an actuall logout-link you should set up a different URL.

For example:

<a href="?action=logout">
    Logout
</a>

And in you PHP:

if (isset($_GET['action']) && $_GET['action'] === 'logout') {
    session_unset();
}

That way the logout logic will only be executed when the user clicks the logout-link.

Visiting:

https://example.com/index.php

Keeps you logged in normally, while visiting:

https://example.com/index.php?action=logout

Will kill your session and log you out.

  •  Tags:  
  • Related