Cookie Or Javascript
I am trying to make a countdown timer for a game. And the problem is, when the user move to another page, then countdown cannot continue the remaining time. I am trying to set a co
Solution 1:
Cookies are sent back and forth with every HTTP request, hence should be avoided for storing unnecessary variables.
To maintain the timer on the server-side, a session is the best choice. It will take care of the cookie business automatically, creating only the bare-minimum cookie overhead to keep track of the session. Session variables live on the server, and are connected to HTTP requests by unique cookies.
Regarding your countdown timer: Since you cannot keep a function running on the server to keep flipping the bits, the best bet is to keep track of the end time.
To initiate a session in PHP, use session_start()
. Then store your values in $_SESSION[]
array, and they'll persist across requests. Here's an example:
<?php
session_start();
if (!isset($_SESSION['endTime']))
{
$_SESSION['endTime'] = time() + 60; // end time is 60 seconds from nowecho"Started a new timer"
}
elseif ($_SESSION['endTime'] > time())
{
echo"Time left: " + ($_SESSION['endTime'] - time());
}
else
{
echo"Time is up.";
}
Post a Comment for "Cookie Or Javascript"