-1

I want to ask about logout times session in PHP.

The code if the user logs into the system:

<?php 

    // the login validation page 

    $the_username = $_POST['the_username'];
    $the_password = $_POST['the_password'];

    $login_date = date("Y-m-d");
    $login_time = date("H:i:s");

    $query = mysqli_query($conn,"SELECT * FROM tbl_user WHERE usr = '$the_username' AND pwd = '$the_password'");
    $result = mysqli_num_rows($query);


    if ($result > 1) {
        $fetch = mysqli_fetch_assoc($query);
        $_SESSION['the_username'] = $fetch['usr'];
        $_SESSION['the_password'] = $fetch['pwd'];
        mysqli_query($conn,"INSERT INTO track_log_user(`id`,`username`,`login_date`,`login_time`,`logout_date`,`logout_time`) VALUES (NULL,`$_SESSION[the_username]`,'$login_date','$login_time','','')");
        header("location:my_menu.php");
    }
    else {
        echo "Your Login Is Incorrect";
        header("location:index.php");
    }

  ?>

The code if user clicks logout button:

<?php
require_once ('connections.php');
// this is logout page when user click button logout in system page

session_start();
$time = date("H:i:s");
$date = date("Y-m-d");
mysqli_query($conn, "UPDATE track_log_user SET logout_date = '$date' AND logout_time = '$time' WHERE username = '$_SESSION[the_username]'");
$_SESSION = NULL;
$_SESSION = [];
session_unset();
session_destroy();
header("location:index.php");
?>

And my question is how if the client is idle or browser error or laptop crash or force close window/tab and their session is ended automatically and logout?

How my tracking user login and logout date-time backend system will working??

I want to make my task easier for making a monthly report for how many customers/clients are visiting and using our website.

Blue
  • 22,608
  • 7
  • 62
  • 92
Yan Erick
  • 17
  • 1
  • 6

1 Answers1

-1

if you want to track user session, then you need to store data into their browser example (cookie).

Syntax for PHP

setcookie(name, value, expire, path, domain, secure, httponly);

Only the name parameter is required. All other parameters are optional.

you can use md5 or any hashing technique to mask your data.

But, if you don't want to store data into their browser, you can create temporary database for the current user session. Whenever the user creates any event (e.g. clicking button, or request a webpage), you can search for the database if he is already out.

After removing data, you can delete the user's temporary data to save space.

Edit: Try using this instead

$datetime = date("Y-m-d H:i:s"); 
$timestamp = strtotime($datetime); //in milliseconds
mysqli_query($conn,"UPDATE users SET logout_timestamp = '$timestamp ' WHERE username = '$_SESSION[the_username]'");

To get the hour/min/sec, first load the stored timestamp of the user in the database, then also get the current timestamp.

//set maximum session (global variable), example 30 minutes
$_MAXIMUM_SESSION_IN_SEC = 60*30;


$timestamp_difference = $new_timestamp - $old_timestamp
if($timestamp_difference/1000 > $_MAXIMUM_SESSION_IN_SEC)
{
    //logout here
}
else 
{
    //remaining time for display
    $seconds= floor((timestamp_difference % (1000 * 60)) / 1000);
    $minutes= floor((timestamp_difference % (1000 * 60 * 60)) / (1000 * 60));
    $hour = floor((timestamp_difference % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
    //echo here
}

Since you are talking about client side. Add javascript. Try this.

<script>
// fetch data from sql
var oldTimestamp = <?php echo $timestamp_from_sql; ?> ;

// Update the every 1 second
var x = setInterval(function() {

  // Get current timestamp
  var currentTimestamp = Date.now();

  // Find timestamp difference
  var timestamp_difference = currentTimestamp - oldTimestamp;

  // Time calculations for hours, minutes and seconds
  var hours = Math.floor((timestamp_difference % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
  var minutes = Math.floor((timestamp_difference % (1000 * 60 * 60)) / (1000 * 60));
  var seconds = Math.floor((timestamp_difference % (1000 * 60)) / 1000);

  // Display the result in the element with id="demo"
  document.getElementById("demo").innerHTML = hours + "h "
  + minutes + "m " + seconds + "s ";

  // If above the session limit, logout the user
  if (distance > maximumSessionInSec) {
    clearInterval(x);
    document.getElementById("demo").innerHTML = "SESSION EXPIRED";
    //add other code here to reload the page
    //or add ajax code to update files in the server
  }
}, 1000);
</script>
  • thank u for ur answer, that will work with cookie feature, but if with session login? when it expires and automatically logout, how can i take that value time (hour,minute,second)? i design that login with session for security reason because if i design that login with cookie, i dont want any stranger come inside my system with fake cookie data. – Yan Erick Sep 01 '18 at 04:38
  • @YanErick try using `$datetime = date("Y-m-d H:i:s"); $timestamp = strtotime($datetime);` .. The timestamp is in milliseconds. You can put timestamp instead of date and time in the database instead. – Leandro Keen Zapa Sep 01 '18 at 05:06
  • can u give me an example query how to update logout date and logout time in database if the user is idle in system and logout automatically without click login button?? thanks. – Yan Erick Sep 01 '18 at 05:18
  • I don't really understand the code above, can you explain it to me? specifically $ _MAXIMUM_SESSION_IN_SEC whether it is additional superglobal from php – Yan Erick Sep 01 '18 at 05:29
  • okay thanks, btw i do not understand what u are making for? i just want to know how my backend system tracking user when they login and logout will working as well if the user force closed the tab or window without click the logout button first. while if the tab / window is closed then that session will end by force and did not recorded in database for my monthly report – Yan Erick Sep 01 '18 at 06:58
  • @YanErick sorry i get confused with your button thing. As we all know, the backend scripts are mostly executed during http request. Most likely, you wanted a script that continuously monitors the session of every user without any client-side communication? Then logouts automatically if exceeds limit? – Leandro Keen Zapa Sep 01 '18 at 07:03
  • @YanErick i guess you need cron job scripts for that. see https://stackoverflow.com/questions/18737407/how-to-create-cron-job-using-php – Leandro Keen Zapa Sep 01 '18 at 07:10
  • not that what i was meant, i doesnt meant scheduler system/program, i just think if the clients in my system login, it will automatically recorded to the database when they logged on with they username as primary key, and then my system will automatically record when they are logged out IF they logout according to the procedure by pressing the logout button. and my biggest problem is how my system record when they logged out, while they will not pressing the logout button as in some conditions, for example sudden power cuts or sudden outages or a computer that breaks suddenly – Yan Erick Sep 01 '18 at 07:31
  • without any communication to the client-side, that seems difficult. I guess the best thing for that is to monitor the client's connection. You should save the client's IP address. – Leandro Keen Zapa Sep 01 '18 at 07:49
  • During bad connection try to save the client's important data. But the client should be logged out if there are indeed important data. So that when he comes back and login, he can recover his data and previous state. – Leandro Keen Zapa Sep 01 '18 at 07:55