How to make countdown timer like in browser games? [closed] - php

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I would like to know how to make countdown timer in PHP. In browser games, for example; when you build up a building or do start a research, a countdown starts for that building etc.. and when you shut down computer or website and open it back from another computer or somewhere else you see that the countdown is still working. Could you briefly explain how it works or what should I search on google to have some idea about it?
Thank you!

You store the time on the server, it could be either the time something started (and you need to know the duration) or the time it ends.
On the client-side, you read this value and make a timer that will tick inside the browser, based on the time you fetched from the server.
Here's a super-simple example that will use browser's localStorage to store the time value. It will show the time passed since you first opened the example: http://jsfiddle.net/ceyw1v5a/
Try refreshing the link to see how the timer value is persistent. I wanted to do it here as a snippet, but it's doesn't allow localStorage for security reasons.
Anyway, because the client-side timer can be easily tampered with, you should never, ever rely on it! That means, say you have a game, and when a certain time expires, you get a gold coin, you should always check for the time expiry on the server because malicious users can easily set the timer to zero and make the server call, but it's up to that server to figure out whether the time had really expired or there's a cheat attempt.
UPDATE
when you build up a building or do start a research, a countdown starts for that building etc..
In that case, the process would go something like this:
user clicks the build button
a server call is made to check if you're allowed to build it (check resources, etc...) and if so, it stores the timestamp when the construction of that particular building has started
based on the construction duration, the timer appears on the client side (the browser), counting down
if the user reconnects, the "currently building" values for all the buildings are read from the server side storage, and the client side timer is relaunched based on the remaining duration
when the timer expires on the client side, a server call is made (as described above), and if the timer on the server side has expired as well (meaning the building is complete), you remove the timer on the client side and show the completed building
if the user leaves before the building is complete and reconnects after it's complete, you simply show the completed building on the client side, no timers needed
About the actual process of getting the data from the server will vary, depending on your app structure. For example, you can make AJAX call(s) to fetch the server data when the game runs, etc.

Use php to get the current time and calculate the end time of the event.
<?php
$event_action_time = "3600"; // 1 hour in seconds
$time = time(); // current time
$endtime = $time + $event_action_time; // future date for event to end
// Store endtime in DB
?>
Now that you have the end time you can query the db for any events that have not ended based on the current time. If there are results you can then assign the end time result to a variable in php and pass it to preferably a jquery countdown.

Related

PHP: how to update user logged in timer without using AJAX calls

I am creating a web application named Online Exam using PHP+MySQL and AngularJS. Now I am getting some trouble on project like changing the user looged in status. Let us take this condition as a example:
Suppose a authorized user/student successfully logged in online exam section(After successfully logged current time will be inserted in the db in exam_start_time column as unix timestamp format and exam_status will be set as 'ACTIVE`.
1hr(60 min) countdown timer is initialize for him/her as per the inserted exam_start_time in db.
Now suppose after 15 min the system shuts down automatically, then if user logged in again(In same system or other) then the countdown timer should be set for 45 minutes only.
Previously I was updating the last_activity_time in our table in every 10 sec(using ajax calls). but now I want to change this way, Is there any way like(socket or network programming using PHP) to update the column.
Here is my table structure which is managing user logged in status
Please give me some suggestions on it.
A Php socket server programming tutorial : http://www.christophh.net/2012/07/24/php-socket-programming/
Sockets, as Pascal Le Merrer mentioned, is IMO your best option. But beware of Apache! Every WebSocket holds one Apache thread, and Apache wasn't designed to do that. when too many (and by too many I mean few dozen) clients connect to your site, it will crash. (I've been there while trying to implement long polling/comet, ended up using NodeJS. If you're using nginx, it is more likely that it will become low on resources and effective, but there are also other ways. Take a look here:
Using WebSocket on Apache server
If you find this uncomfortable/hard to learn, try also another idea:
try to add hidden iFrame to your exam page, pointing to prepared site that updates database row. Use javascript to refresh this page every 10-15 seconds. Every refresh causes update of specific row in DB, using current date and time. It should work (not tested, but give it a try).

mysql - php countdown timer - server side

I am using php and mysql and have no java knowledge. After searching I have found many countdown timers for javascript but they are client-side. I am looking for something that is server-side based.
I have a table in mysql with a column called TimeRemaining. That column stores future time records. I need to load the record with the least time remaining so that when it hits zero that record is removed from the table and a new countdown timer begins with the next record with the least amount of time remaining. Also, if a new record is inserted with less time remaining than the previous record with the least time remaining, the timer needs to be updated with the new record.
Is this possible and/or recommended through using triggers to update an event in mysql or can I create a countdown timer in php.
Thank you all for any help.
Edit:
I mentioned Java/Javasript because I would like to avoid it as I have no knowledge of it and through research I have seen most posts using java.
For a better understanding of what I want to do, multiple users are banned from creating posts in a forum for 7 days. I have a table in mysql that stores that ban and the time it expires. I need to automatically remove that record from the table when the 7 days expires. The user should have no control over this timer. I do not need to display the time remaining on a webpage. I need this to happen in the background with no user intervention. Is that clearer ?
You want to do this client-side. On pageload, you can pull the countdown time from the SQL table and client-side countdown THAT time. Once the time is complete, you can do a call (synchronous or AJAX) to the server (PHP) again to remove that record.
Considering you said you have little knowledge of javascript I would make a little iframe in your page that refresh automatically and show the last time checked accordingly.

Dynamically checking mySQL database to see if a currenttime has passed a datetime stored in the database

basically i have a series of countdown timers for auctions on my site. i do this by storing the countdown end time in the database and use javascript to create the countdown. i was just wondering how i could have the web-server constantly check whether the countdown has finished and if is has, dynamically change the status of the auction from "not finished" to "finished". should i have a constantly running script on my web-server? that keeps querying the database to check if the countdown end-time has been reached?
p.s. im using apache, mySQL, and PHP
any views or help is appreciated!
Johnny
Constantly checking would not scale at all. It's unlikely the end time would change, so you can just deliver the end times of each auction to the web page and use javascript to change the status to finished when that time reached.
Sure, someone could edit the javascript and change the end times, but the client is only for display. You can do one final call to the server at the end time to check if the auction was extended. The server remains that authority. Any submission still needs to be check against the server time, not whatever was displayed on the user computer.
For me the logic goes like this
Load the default end time using database value and run counter through javascript.
when elapsed time is about to reach the auction end time say just 1 or 2 seconds before, you can check if the end time has changed and return the new value and feed it back to Javascript timer.
Above is applicable only if you increase end time for some reason.
If not than you can solely rely on javascript to count time for you and when end time is reached with javascript counter just make a quick ajax call to update your database (if it is required at all)
You should always load end time to your javascript function from your database

Countdown timer with random number generator

I am running a sweepstakes like thing and want my users to all be able to load the page and have the exact same countdown and number generator running. I tried this in AS3 but each user caches their own swf file and gets a different result from the random number generator, and the as3 countdown is a few seconds off from each user. How would I go about making a countdown that is the exact same for each user looking at it at the same time and then a random number generator where every user will see the same result it gives? Is it even possible?
Sorry I wasnt clear on this. I would like to have it where the viewers could see the number being generated when the timer runs out. Kind of like watching the lotto on TV. Again, not sure if this is possible.
I have looked around, I know as3, some php, and some javascript. I have given up on doing this in flash.
Assuming I understand correctly what you want, store a random value (RV) every time someone accesses the page associated with a UNIX timestamp in seconds. Make time column unique, then if another request is made the same second, the random number is going to be taken out of the database.
Store the timer result in a table, show users the stored random number. Then when needed simply create another random number, store again, show user. Repeat.
Every user that come to that page , first print the time from the server so every user that will come and if your server time is 12:00 am for example , you will show him 12:00 am.
And then with Ajax refresh this time every X seconds ajax will send a request to the server and the server will tell you the time to display.
Keep the random logic on your server and when your application logic will say to change to a different number the server will return a different number and your clients will get it on the next pull ( ajax ) .
I hope that answering your question.
I'm not too familiar with flash, but what I would do is make the countdown happen client side using javascript's getUTCSeconds(), getUTCMinutes(), getUTCHours() etc to figure out current time verses end time of the counter (end time in universal time code).
Then you could use php to generate the random numbers (and a corresponding remaining time associated with it? how often do you want these?) and store it in a location for later retrieval (database, or file or some such). You could use ajax to grab the random number at the specified times
for more about js date/time functions w3schools has a pretty good resource:
http://www.w3schools.com/jsref/jsref_obj_date.asp
This is possible.
All logic should be stored on the server side. Use Flash only to show results.
Countdown: create it with php, store on the server side in the storage (database, memory, files, whatever). All clients (written on Flash) request counter value and display the counter on the client side starting from the value taken from server.
Lotto results are also generated on the server and passed to the clients. On the first hand you may generate intermediate results on the server and read them one by one by the clients, but I'd generate all results at once and pass them to the client.
Intermediate results can then be synchronized with the counter.

Few issues with creating a web based chat system

I've decided to create a web based chat system for the experience. I'm using a mixture of AJAX(jQuery), PHP, and JSON to transfer the data. Now that I've started thinking about certain things, I've come to a mind block.
Right now, I use javascript to post the last loaded message id to a php file that queries the data and echoes new posts in json and then displays those posts in order on the page. However, the dates don't reflect the current time for the user. Since I use php to get the current time, I have no idea how to display the correct time to the user which takes into account of their time zone. Second, how would I incorporate a who's online list with this method? I could create a separate table and update it when a user creates a session and delete their name when they end the session; but what if they don't close it properly? Should I just add their last sent message into the the table and if it's been about 5 minutes since their last message consider the user disconnected? Lastly, is the method I'm using to collect new posts efficient? This there a better way to go about this? I appreciate any input.
This seems related: Determine a User's Timezone
I'm going to make you go there for the code snip so you give proper credit with your upvotes.
I get the impression that Javascript is the best/easiest way to get that data.
What I would probably do is use GMT or some other fixed time zone for all your server stuff and then just adjust that with js once it hits the browser depending on their time zone. Either that or just collect it once at the start of the conversation and adjust your output accordingly. There might be advantages to either way.
Edit:
Oh yeah, about the "who's online" I think you're headed in the right direction. I might suggest 2 lists. "Who's active" and "Who was active recently"
That way you can put people inactive after 5 mins and consider them disconnected after 10 or something. I guess it's about the same but it seems more accurate to me somehow.
The other option would be to set an ajax request to automatically fire of a request every minute or so. When they stop then you know the user is gone.

Categories