在会话中保持时间并比较差异

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();
}

?>

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.