Using Session Variables for Comparing Times

 

Introduction.  Now we will develop two fairly simple PHP files.  The first will set the current time into a session variable.  This information will then be posted to another page that displays the session variable for when this process started and the current time.

This just demonstrates how a session variable stays the same unless it is reassigned.

The first page should be called current_time_session.php.

 

<html>
<head>
<title>Setting the Current Time to a Session Variable</title>
</head>

<body>
<?php
session_start();
$_SESSION["session_start_time"] = date('H:i:s A');
?>
<center><h2>The time at the start of the session was
<?php echo $_SESSION["session_start_time"]; ?>
<p>please wait some time<br>before pressing the button</p>
</h2>
<form action="current_time_compare.php" method="post">
<input type="submit" value="Get Current Time" style="font-size: 14pt; font-weight: bold">
</form>
</center>
</body>
</html>

 

Notice how the session variable is set and displayed.  You should wait some time before posting to the next page which should be called current_time_compare.php.

 

<html>
<head>
<title>Comparing the Current Time to a Session Variable</title>
</head>

<body>
<?php
$current_time = date('H:i:s A');
?>
<center><h2>The time at the start of the session was
<?php
session_start();
echo $_SESSION["session_start_time"];
?>
<p>The current time is <?php echo $current_time; ?></p>
</h2>
</center>
</body>
</html>

 

This illustrates how the session variable is retained.