Hello guys, does anybody know how to create a timer in PHP that runs even when the user goes offline. I am working on a project, actually a text based game, that needs a timer that runs continuously even after the user goes offline. The game is something like mafia wars in Facebook. It has an energy regeneration timer that needs to run continuously while the players energy is not full.

For example, the player's max energy is 20. then, he uses 5 energy points to do a certain job. His energy goes down to 15. Let's say the energy timer is set to 3 minutes before it adds one energy point. The timer will be counting down from 3:00 to 0:00. If the timer reaches 0:00, the player's energy will be incremented by 1. Then, the timer will be reset to 3:00 minutes. This will go on until the players energy reaches 20 even after the user goes offline. Is this possible? I really hope it is.. please help.. thanks in advance... I'm kinda new in php so please walk me through it.. ^_^

There is no way to do that.
What you can do is store the player logout time, and when he logs in again, compare the times and do necessary changes.

There is no way to do that.
What you can do is store the player logout time, and when he logs in again, compare the times and do necessary changes.

Thanks for the reply. I have some questions.. hope it's okay.. Can you teach me how to do that? How do you insert,retrieve and compare date and time in mysql database? How should the database look like, i mean the char type and other settings? :S

Is it possible to have and display a live timer in PHP that will not reset if the page is reloaded?

Thats javascript, PHP is server side language, which runs only when it's requested.

And about the time comparison... I do want that you try for yourself, so make some effort, I will just outline the main concept.

I admit that you already have a table of players or something like that. The deal is to have a column in that table which holds the user logout time. (You simply execute a query which inserts the current timestamp generated by the date() function, when the user logs out).
When a user logs in, the time of last logout is requested from the users table and compares with current date and time.
So you have two dates, now use the mktime() to both dates and compare the results.
According to result do your changes to the profile.

All the function examples you will find on php.net

Member Avatar for diafol

As mentioned, you could use php to log the last action/logout of the user in a DB (or cookie). However, the practicalities of doing this are far more involved than they would first appear. For instance, if a player did not do anything for 3 minutes, nothing would happen to the 'points' as php is 'spent' before the browser shows the page.

Also as mentioned, you need javascript:

http://www.w3schools.com/js/js_timing.asp

That may give you an idea of how to use time functions in js.

Mixed with Ajax (usually js with php [or XML]), you can create some powerful time-dependent functions ideally suited to your type of game. But a caveat: because ajax functions make calls to the server, if you have lots of players online at the same time, your server could get bombarded with calls -> major problem.

Server calls will be unavoidable if the game is meant to be played against/with other players. You may find that other languages would be more suitable, e.g. Java (I know absolutely nothing about it though).

Thats javascript, PHP is server side language, which runs only when it's requested.

And about the time comparison... I do want that you try for yourself, so make some effort, I will just outline the main concept.

I admit that you already have a table of players or something like that. The deal is to have a column in that table which holds the user logout time. (You simply execute a query which inserts the current timestamp generated by the date() function, when the user logs out).
When a user logs in, the time of last logout is requested from the users table and compares with current date and time.
So you have two dates, now use the mktime() to both dates and compare the results.
According to result do your changes to the profile.

All the function examples you will find on php.net

Okay, I'll try to do that. Thanks a lot for your time amd..

As mentioned, you could use php to log the last action/logout of the user in a DB (or cookie). However, the practicalities of doing this are far more involved than they would first appear. For instance, if a player did not do anything for 3 minutes, nothing would happen to the 'points' as php is 'spent' before the browser shows the page.

Also as mentioned, you need javascript:

http://www.w3schools.com/js/js_timing.asp

That may give you an idea of how to use time functions in js.

Mixed with Ajax (usually js with php [or XML]), you can create some powerful time-dependent functions ideally suited to your type of game. But a caveat: because ajax functions make calls to the server, if you have lots of players online at the same time, your server could get bombarded with calls -> major problem.

Server calls will be unavoidable if the game is meant to be played against/with other players. You may find that other languages would be more suitable, e.g. Java (I know absolutely nothing about it though).

thanks ardav.. I'll try to use js as well.. oh, and by the way, the link was helpful. About the java thing, I have very little knowledge about it, and I find it hard.. :D

Anyway, I think I'm getting closer to make this work. I really appreciate it guys.. ;)

I'll be posting post the results later..

You may already be thinking of this, but one idea is to make two timers.

One is a PHP timer(as described above, using dates or timestamps).

Two, if you want to enhance the user's experience, make a JavaScript timer as well, which doesn't alter the user data in any way but provides a visualization for the user. That way you don't have to worry about clogging up your server with excessive queries.

Also, for the PHP timer, keep in mind that if you want the regen to happen every 3 minutes, what happens if the user loads the page at 4 minutes from his last action? He needs to get 1 energy point, but you can't simply the current timestamp in the database, or else he will be shorted a minute of regeneration.

I use the following code for this:

<?php
$con = mysql_connect("yourhost","YourDB","YourPassword");
if (!$con)

{
die('Could not connect: ' . mysql_error());
}

mysql_select_db("YourDB", $con);

$result = mysql_query("SELECT * FROM YourDb WHERE UserID=$_COOKIE[UserID]");

if (!$result)
{
die('Login Timed Out');

}

setcookie("UserID", $_COOKIE[UserID], time()+3600);

while($row = mysql_fetch_array($result))
{
$TimeStamp = $row['Timestamp'];
}


$t = mktime();

$TimeCheck = $TimeStamp - $t;

$a=0;

while($TimeCheck<=0)
{
$a++;
$TimeStamp += 10800;
$TimeCheck += 10800;
}

while($a>0)
{
$a--;
//Code you want to be time activated
}
?>

You just require() or include() that at the top of each page. Doesn't need you to mess about with login timers or anything, it works in 'real time' and will update on login. You can modify it pretty easily to update whenever any data about the user in question is called for any reason (including other players looking at it) doing so effectively keeps it permanently updated.

It requires you to fill the TimeStamp with the current time or the current time + 1 'tick' (10800 seconds in my case) when the account is created, I find stroing the TimeStamp as an integer easier, but ymmv. In addition you need to be using cookies that track your user at login, but as that is extremely standard I figure you will be.

Member Avatar for diafol

@TiberS
You think he's still searching after over 6 months?

@TiberS

Thank you so, so much for that code.

Hello guys, does anybody know how to create a timer in PHP that runs even when the user goes offline. I am working on a project, actually a text based game, that needs a timer that runs continuously even after the user goes offline. The game is something like mafia wars in Facebook. It has an energy regeneration timer that needs to run continuously while the players energy is not full.

For example, the player's max energy is 20. then, he uses 5 energy points to do a certain job. His energy goes down to 15. Let's say the energy timer is set to 3 minutes before it adds one energy point. The timer will be counting down from 3:00 to 0:00. If the timer reaches 0:00, the player's energy will be incremented by 1. Then, the timer will be reset to 3:00 minutes. This will go on until the players energy reaches 20 even after the user goes offline. Is this possible? I really hope it is.. please help.. thanks in advance... I'm kinda new in php so please walk me through it.. ^_^

Hi maybe this will be useful

timer.php

set_time_limit(0); 
while(1){
echo 324;
sleep(5);  
//make some stuff
file_put_contents("/opt/lampp/htdocs/sockets/STUFF.txt",time()) ; 
}

To run timer in background we will use proc_open

$descriptorspec = array(
   0 => array("pipe", "r"),  // stdin 
   1 => array("pipe", "w"),  // stdout 
   2 => array("file", "STUFF.txt", "a"), // stderr 
);
$process = proc_open("/opt/lampp/bin/php -f ".__DIR__."/timer.php", $descriptorspec, $pipes) or die('error');

Why do u use PHP for timer...Its server-side...will put a lot of load on your server...Try using javascript...You'll get loads of scripts for that...

OR use CRON

Further discussion on this is not necessary.

1- OP's question was regarding something that could keep track of a game user's energy regeneration. This was answered, a timestamp comparison(to determine how much time has passed) can be used to distribute any necessary energy when the user loads the page.

2- If you use a timestamp comparison as listed above, it is not resource intensive on your server.

3- Javascript is client-side, meaning it cannot update the user's energy in the DB unless you're talking about using Ajax and increasing server stress.

4-This discussion is old. If anyone has a specific question about timers, start a new thread.

Member Avatar for diafol

Just for completeness, w3fools is a great site, but I think w3schools actually uses functions in its examples, not code. The 'javascript statement' is unfortunate. I agree you never place code in a setTimeout.

I've just posted it for future ;)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.