0
votes

I am trying to saving the user login time in session array so that i may calculate the logout time later. My login_success file saving time in session successfully but the remaining two files are not saving the same time in sessions. Help me in finding out the problem please.

login_success.php

$sql2 = "SELECT DATE(login_time) AS date_part, TIME(login_time) AS time_part FROM log where username = '$USERNAME' ";
$res = mysqli_query($link, $sql2);

while ($row = mysqli_fetch_array($res))
{
    echo $row['time_part'];
    $_SESSION['time'] = $row['time_part'];

}

login.php

if(isset($_GET['action']) && $_SESSION['time'] )
{
    session_destroy();

    $start_time = $_SESSION['time'];
        $life = time() - $start_time;
        $_SESSION['life'] = $life;
        header('location:session_life.php?act=life');
}

session_life.php

<?php
include_once './include/db_connection.php';
session_start();
print_r($_SESSION);
if(isset($_GET['act']))
{
    if(isset($_SESSION['life']))
    {
        $lifee = $_SESSION['life'];
        print_r($lifee);
    }
}
1
have you put session_start(); on top of your script? - n-dru
yes...................... - bc110402307 Syed Zeeshan Haide
Yes .................. - bc110402307 Syed Zeeshan Haide
can you show us the output of echo $row['time_part'] - Vasil Shaddix
@VasilShaddix Please see my updated question. - bc110402307 Syed Zeeshan Haide

1 Answers

2
votes

When you call session_destroy() in your login.php script, you have to call session_start() again in order to use $_SESSION variables again.

session_destroy() destroys all of the data associated with the current session. It does not unset any of the global variables associated with the session, or unset the session cookie. To use the session variables again, session_start() has to be called.

Source: php.net


In comment section you also mentioned you are getting different time format than you would like to.

Since time() function you use returns the current time measured in the number of seconds since the Unix Epoch (January 1 1970 00:00:00 GMT) and you are subtracting two values in this format, you get a difference in the same format.

With that knowledge, you can recalculate it to the real value you are interested in. For more reading about this topic, try looking at these links & questions:

Edit: Converting timestamp difference to Hours:Minutes:Seconds

$timeStampDifference = 1458290809;
echo gmdate("H:i:s", ($timeStampDifference/1000000)); // This should do the trick