0

I have a code that I want to check for time differences. This code below will check the the time start and time end then it will display the total time taken.

When I first load the page, the time will initialize in session. After that I will wait for a few seconds and then change the $test variable to 1. The if will then executed and display Total time taken. Then the session will be destroyed and reset everything.

However the code does not works. Time in microseconds to reflect the waited seconds is not shown??

<?php
        if(!isset($_SESSION['time_start'])){
        $_SESSION['time_start']=microtime(true);
        }

$test ='';

if (!empty($test)){

    $time_end = microtime(true);
    $display = $time_end - $_SESSION['time_start'];

    echo "Total time taken: $display";
    session_destroy();
}

?>
sg552
  • 1,521
  • 6
  • 32
  • 59
  • 2
    How are you waiting and changing the variable, in the php script itself? If it is in another request, `$test` will not exist and your original script will have finished running. And you need `session_start()` at the top of each script. – jeroen May 14 '14 at 13:08
  • I'm sorry. I forgot the `session_start()`. It works now. – sg552 May 14 '14 at 13:17
  • @sg552 why are you storing `microtime` in the `$_SESSION` superglobal? I don't think your code is doing what you think it's doing... – LifeQuery May 14 '14 at 13:33

1 Answers1

1

Rather than doing this (and manually changing & refreshing the script after you've modified the $test variable):

$test ='';

if (!empty($test)){

Try this script instead:

session_start();
$current_time = microtime(true);

if (isset($_SESSION['time_start']) && !empty($_SESSION['time_start']))
{
    $time_end = $current_time;
    $display = $time_end - $_SESSION['time_start'];

    echo "Total time taken: $display";
    $_SESSION['time_start'] = '';
    session_destroy();
}
else
{
    $_SESSION['time_start'] = $current_time;
    echo "Initial time variable set, press refresh.";
}

I think the main issue is that you missed calling 'session_start()' at the top of the script.

What will happen with the above script is the 'else' part will run first as the 'time_start' part of the session isn't initially set, and/or is empty. This will set the data into the session. The next page load the if statement should run and it will display the time between refreshes.

Johneh
  • 84
  • 5