PHP Session count and restart session
From w3cyberlearnings
Contents |
using expire session and page refresh to implement a counting game
- The page refresh every count
- When the count reach 60 the message display to the user
- Finally, the count start from zero again and the repeat count
create page (mycountpage.php)
- This is a simple PHP page without any PHP script.
- We let the page to be refresh every second.
- Page refresh: <meta http-equiv="refresh" content="1">
<html> <head> <meta http-equiv="refresh" content="1"> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Time out Page</title> </head> <body> </body> </html>
add session and PHP script
- We start the php session.
- Initialize the $time_diff=0 and $youhit=null;
<body> <?php session_start(); $time_diff = 0; $youhit = null; ?> </body>
add the count logic
- Add additional logic for checking the count
<?php session_start(); $time_diff = 0; $youhit = null; // check to see if $_SESSION['timeout'] is set if (isset($_SESSION['time'])) { // count time $inactive = 60; $time_0 = time(); $time_1 = $_SESSION['time']; $time_diff = $time_0 - $time_1; if ($time_diff > $inactive) { $youhit='Finaly, you won!!'; session_unset($_SESSION['time']); } } else { // set when not set $_SESSION['time'] = time(); } ?>
add the page body for user to see
- This page place to let user to see the count take place.
- And, display message when the count reaches 60.
Welcome to Time Test Page! <p>Time: <?php echo $time_diff; ?></p> <p> <?php if (isset($youhit) && !empty($youhit)) { echo 'Yes, ' . $youhit; } ?> </p>
final script (mycountpage.php)
- This is the final version of the example.
<html> <head> <meta http-equiv="refresh" content="1"> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Time out Page</title> </head> <body> <?php session_start(); $time_diff = 0; $youhit = null; // check to see if $_SESSION['timeout'] is set if (isset($_SESSION['time'])) { // time in second (1 min) $inactive = 60; $time_0 = time(); $time_1 = $_SESSION['time']; $time_diff = $time_0 - $time_1; if ($time_diff > $inactive) { $youhit='Finaly, you won!!'; session_unset($_SESSION['time']); } } else { $_SESSION['time'] = time(); } ?> Welcome to Time Test Page! <p>Time: <?php echo $time_diff; ?></p> <p> <?php if (isset($youhit) && !empty($youhit)) { echo 'Yes, ' . $youhit; } ?> </p> </body> </html>