Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use time() to count how many seconds you logged in

I'm creating a script and let's say I have a user/pass to enter and once it's entered another page will be redirected and in that page will show a line sayingi you have been staying here for xxx seconds.

I'm using $_SESSION at the moment but I'm not sure how to set up so time() will start counting after logged in.

this is my index.php script

if((isset($_GET["user"])) || (isset($_GET["pass"])))
{
    if(($_GET["user"] == "a") && ($_GET["pass"] == "a"))
    {
        session_start();
    $_SESSION["auth"] = 1;
    $_SESSION["username"] = $_GET["user"];
    $_SESSION["loginTime"] = time();
    $_SESSION["timeLogged"] = time() - $_SESSION["loginTime"];


    header("Location: 1.php");
}
else
{
    echo "Incorrect login data";
}
}

this is my 1.php script

session_start();
if(!(isset($_SESSION["username"])))
{
    header("location: index.php");
}
else
{
    echo "Welcome " . $_SESSION["username"] . "<br/>";
    echo "You have been logged in for " . $_SESSION["timeLogged"] . " seconds.";
}
like image 672
Tsuna Avatar asked Oct 22 '22 16:10

Tsuna


1 Answers

Using $_SESSION (as you mentioned)

Page 1 - store the current time (or any time for that matter) in a session (cookie)

$_SESSION['startTime'] = time();

Page 2 - subtract the current time (meaning the time page 2 is visited) by the time we passed in the cookie (created on Page 1)

if (is_int($_SESSION['startTime'])){ // if the cookie exists:
    $difference = time() - $_SESSION['startTime'];
} else { // if the cookie does not exist:
    echo "You have been here some time in the future";
}

Anyway... something like that might work


EDIT - with the code you provided:

Move $_SESSION["timeLogged"] = time() - $_SESSION["loginTime"]; to your 1.php script. You need to calculate the difference once you get to the second page :)

what you had:

$_SESSION["loginTime"] = time();
$_SESSION["timeLogged"] = time() - $_SESSION["loginTime"];

That last line is = current time - (variable that also = current time) = 0

like image 56
d-_-b Avatar answered Oct 24 '22 11:10

d-_-b