Jump to content

[SOLVED] PHP and Javascript timer with sessions


noj75

Recommended Posts

Hi all,

 

For the last week I have been pulling my hair out trying to figure out how to impliment a timer into my pages and have it countdown from 4 minutes 59 seconds.

 

A simple countdown using javascript would solve the coundown issue but I need the timer to remain the same on everypage as it counts down - !important. Once it has counted down I need to execute a mysql query and then it starts again from 4mins 59secs. (Like mobwars or mafiawars for cash/energy).

 

I found this on another website but dont know how to fill in the blanks:

 

<?php
   session_start();

   //to reset the saved countdown
   if (!empty($_REQUEST['resetCountdown']))
   {
       unset($_SESSION['startTime']);
   }

   if (empty($_SESSION['startTime']))
   {
       $_SESSION['startTime'] = time();
   }

   //In seconds
   $startTime = time() - $_SESSION['startTime'];
?>
<script type="text/javascript">
var countdown = 60; //in seconds
var startTime = <?php echo $startTime; ?>;

startCountdown(startTime, countdown);

function startCountdown(startFrom, duration)
{
   //countdown implementation
}
</script>
<?php echo $startTime; ?>

 

That is a start but when the page is refreshed it shows the counter going up?

 

As I said I need the counter to perminantly display whilst counting down, accross ALL pages, execut a query, start again.

 

I would really appreciate it if any of you top coders out there could help me finish it. I am a beginner at PHP and know NOTHING about javascript.

 

PLEASE HELP, its driving me MAD !!  :'(

 

Many kind regards.

Link to comment
Share on other sites

Familiar with making ajax requests at all?  I would make an ajax call every 5 seconds or so to update a session variable.  (or every second if you really need it to).  On the next page load you can check that session variable - and then execute your Javascript accordingly.

Link to comment
Share on other sites

Oh Dear, Please don't tell me your suggesting he store the timer that effects the users gameplay, in the javascript (which can be manipulated). To then be sent to, and trusted by, the server.

 

That means that Javascript does the counting and PHP just then accepts what the browser told them the last update was and ran it again.

 

Dear dear.

 

PHP needs to do the counting. All of it. PHP should store the last update time in the session/database then execute an update based on that last time. Javascript, being the potential security flaw that it is in this situation, will pretend to. PHP will tell javascript the last update time, and javascript will continue to countdown from there, pretending it is the real timer. There really should be no need for any Ajax. If there is, there shall be slapped wrists.

Link to comment
Share on other sites

Oh Dear, Please don't tell me your suggesting he store the timer that effects the users gameplay, in the javascript (which can be manipulated). To then be sent to, and trusted by, the server.

 

That means that Javascript does the counting and PHP just then accepts what the browser told them the last update was and ran it again.

 

Dear dear.

 

PHP needs to do the counting. All of it. PHP should store the last update time in the session/database then execute an update based on that last time. Javascript, being the potential security flaw that it is in this situation, will pretend to. PHP will tell javascript the last update time, and javascript will continue to countdown from there, pretending it is the real timer. There really should be no need for any Ajax. If there is, there shall be slapped wrists.

 

Hi Paystey, your explanation is very interesting and sounds safe, could you possibly help me further?

 

I really would like to find a solution. Willing to pay if required (reasonable amount) :-\

Link to comment
Share on other sites

Hi

 

I would go with the Ajax solution.

 

Firstly on your initial login save a session variable which stores the time as a number of seconds.

 

Have a small php script that when called takes that time and subtracts it from the current time in seconds, and then does a mod of it by 300 (ie 300 seconds, 5 minutes),then subtract it from 300. This should give you the number of seconds since the last time the 5 minute "segment" started. Then just return this.

 

Each page then needs an Ajax call to this script occasionally to grab that value. Use setInterval to have a small function run when required to call the Ajax. You could do this every second but the server might not appreciate it and not really necessary. I would be tempted to do a call every second but only call the server every minute or so. For every other call just calculate it from the last call. However as mentioned above, do not trust a time stored on the users machine that a malicious user could manipulate.

 

All the best

 

Keith

Link to comment
Share on other sites

Thanks for that,

 

I have now chosen a different approach using cron jobs and a mixture of PHP and JS.

 

I have set up a cron job that updates two tables every 5 minutes. The first table is to update the players rep by 1 point.

 

The second updates the current time "h:i:s" to show when it was updated. All that is in a seperate file.

 

I am trying to use the code below to work out the last time the cron was updated, then minus the current time from that which will then give me time left untill the next cron update. I need to convert that to seconds and enter the value into the JC code "secs".

 

Please see the code below:

 

<?php
$dTqry = "SELECT * FROM $mycrondb";
$dTres = mysql_query($dTqry);
$dTrow = mysql_fetch_array($dTres);

$dbtime = $dTrow['timed']; // h:i:s stored in the database eg: 10:02:39

$dbt = date('h:i:s', $dbtime); // database value
$crt = date('h:i:s'); // current time
$newtime = $crt - $dbt; // trying to get the difference
?>

<script type="text/javascript">	 
/* START TIMER */
var timeInSecs;
var ticker;

function startTimer(secs) {
timeInSecs = parseInt(secs);
ticker = setInterval("tick()", 1000); 
}

function tick( ) {
var secs = timeInSecs;
if (secs > 0) {
timeInSecs--; 
}
else {
clearInterval(ticker);
startTimer(300);  // start again from 5 minutes
}

var mins = Math.floor(secs/60);
secs %= 60;
var pretty = ( (mins < 10) ? "0" : "" ) + mins + ":" + ( (secs < 10) ? "0" : "" ) + secs;
document.getElementById("countdown").innerHTML = pretty;
}

startTimer(<?php echo $newtime; ?>);  // time left untill next cron update

</script>

<span id="countdown" style="font-size:12px;"></span>

 

Now I am totally stuck on how to finish this little script. Anyone have any ideas?

 

Kindest regards

Link to comment
Share on other sites

Hi

 

I think I would just do the conversion in the SQL (using unixtimestamp() ).

 

Had a play with the method I suggested:-

 

Basic script to get the time:-

 

<?php
session_start();
if (!isset($_SESSION['StartTime']))
{
$_SESSION['StartTime'] = time();
}
$Start_Time = $_SESSION['StartTime'];
$ElapsedTime = 300 - ((time()-$Start_Time) % 300);
$Mins = intval($ElapsedTime / 60);
$Secs = $ElapsedTime % 60;
echo $Mins.":".$Secs."||".$ElapsedTime."||".$_SESSION['StartTime']."||".time();
?>

 

And a basic page with a bit of javascript to display it

 

<html>
<head>
<script type="text/javascript" src="Includes/zxml.js"></script>
<script>
var fred = setInterval("getTime()",1000);
var curtime = 300;
function getTime()
{
if ((curtime % 10) == 0)
{
	if (zXmlHttp.isSupported())
	{
		var oXHR = zXmlHttp.createRequest();
		var QueryString = "TimerAjaxTest.php";

		oXHR.open("get",QueryString, true);
		oXHR.onreadystatechange = function () 
		{
			if (oXHR.readyState == 4)
			{
				if (oXHR.status == 200 || oXHR.status == 304)
				{
					var arrInfo = oXHR.responseText.split("||");
					document.getElementById('TimerDisplay').innerHTML = arrInfo[0];
					currtime = arrInfo[1];
				}
			}
		};
	}
	oXHR.send(null);
}
else
{
	curtime--;
	var Mins = parseInt(curtime / 60);
	var Secs = curtime % 60;
	document.getElementById('TimerDisplay').innerHTML = Mins + ":" + Secs;
}
}
</script>
</head>
<body>
<div id='TimerDisplay' >
Timer Not Set Yet
</div>
</body>
</html>

 

All the best

 

Keith

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.