mysql - php countdown timer - server side - php

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.

Related

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

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.

Timer mysql php check

It's bugging me for a day now and I really cant find out, I have a basic login/register page, and when registering, a timestamp is stored in the mysql database(table timer, column cooldown):
$settime = mysql_query("INSERT INTO `timer` (`cooldown`) VALUES(0)") or die(mysql_error());
What I want to do now (I'm creating a browser mmorpg), Is when I do a specific POST request, I want a timer in my database to go off. This timer should be 1 minute, and also be shown for users, like: <?php echo $timer['cooldown']; ?> Whenever the timer is = 0, I can do a specific function again, and the timer will be set to 60 seconds again.
Sorry for the lack of knowledge but I can't find out anywhere how to do this.
What you're trying to do here - a background job - goes against the web development principle of a request-response cycle in the shared-nothing environment of PHP.
But there are several ways to break up the rigid cycle:
If you just need to do some DB updates after 1 minute, you can use MySQL events: http://dev.mysql.com/doc/refman/5.1/en/events.html
If the function you want to call is not running too long, you can check on every user request if there are entries in the timer table that are older than 1 minute.
Create a PHP script that is called by a cron job every minute. It checks if there are unhandled items in the timer table and does something with them.
Create a PHP daemon script that wakes up every minute to check.
If you need to change something on the user page after 1 minute, doing the PHP script call client-side with a JavaScript timeout and AJAX or websockets is the better option.
For displaying the countdown to the user, you have to use JavaScript. If you are using the server-side timer, you can use it just for display purposes, hiding the countdown when it's finished. To work around the "user opens new page before timout is finished" problem, put the data for the remaining seconds in an HTML data attribute where your JavaScript code can read it.

Saving last SQL query state in PHP

For a two-player game, I need to send updated data to player every 30 seconds.
I have a table (ideally 4 tables) from where I need to select data and sent to user once he/she login. Since it is multi-player interaction game, data needs to be sync every 30-60 seconds.
My problem is, I've a very heavy query to run every 30-60 seconds. So ideally, I should send only updated and new rows to the player during sync (Its also a front end requirement for IPhone/Android game, app don't want whole data during every sync operation).
I went through MySQL: difference of two result sets and hope I'll get only updated/new records through SQL but problem is, how do I save result of last query.
Even if I save first result in Session (probably not recommended) that record will be useless as soon as new row inserted or updated. Updating session record again will definitely put lot of pressure on the server.
Can someone please suggest the best way to achieve this requirement; Not detailed solution, just some hint/link will be sufficient.
Basically, this isn't that hard. Let me provide you with a step plan.
Add a datetime field to each table you want to do this on
In each of your updating queries, set this field to NOW()
Make sure that the application adds the time of its last update to all its requests
Have the server add the time of the update to result it send to the app (which also sends the updated rows)
Can't you just timestamp everything?
Give every row in the tables a timestamp called something like "last_updated"
In the query, filter out all entries with a last_updated that is before the last time the query was executed (or possibly the latest last_updated that the client got the last time it called the server)

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

PHP, how do I calculate total online time of a user?

What is the best way to calculate the total time spent by a registered user on the site? ...under these conditions
1) User logs out normally.
2) User can simply close browser.
3) User can auto-login next time he comes back.
I think the best way to do this would be to find the time spent by the user on each page and keep adding them to his total time instead of checking for the whole site. But I don't know how to implement that....please help
You can't find the exact time he leaves the system, unless he logs out. Even then, he might be browsing the site while logged out.
The approximate way to do this would be to set the start time in the session and keep incrementing the time everytime he visits a page.
So the first time the user comes to your site at time T, you will
Create a session and put the start time there
Add the total time as 0
For all subsequent requests you would
Check the start time and compare that with the time now and get the difference
Add that time to the total time
This method will not give you the time the user spent on the last page. But it will give you something to work with.
You can do this with JavaScript and a separate PHP script.
The javascript code reacts to events that mean that an user is active (such as mouse/keyboard/resize events) and invokes the php script.
The php script compares the time when it last received a request to the current time and checks if the difference is over a certain threshold (i suggest something like 10-30 minutes to prevent single-click sessions from adding up) nothing happens.
If the threshold is not reached then the difference between the two timestamps is added to the total sum in the database.
Afterwards (in both cases) the last request time is set to the current time and the script ends.
If you also want to know when the user closes your website pages you can subscribe to unload events and/or implement an heartbeat script that calls a PHP script every X seconds.
you have 2 approaches, either to create a log table in your DB to track each user (by ID) logins and logouts and then calculate the time difference between the two in each record for the specific user and then sum all of that. OR you go more complex and make 4 columns in your DB->usertable (logintime 'timestamp' - logouttime 'timestamp' - lastactive 'timestamp' - onlinetime 'int') and update each column as their names say by code according to user activities. then alter the Session.php script in the System/libraries directory at line 105 exactly after if ( ! $this->sess_read()) before the system creates a new session and write a code to check if the 'logouttime' is not the same as 'lastactive' time (to avoid session timeout expiry misunderstood in the next code) if both fields not the same, update your DB to make 'logouttime' equals 'lastactive' then at line 107 exactly after: $this->sess_update(); write a code to check if the 'logouttime' equals the 'lastactive' (and you will make that happen earlier in your logout.php script) write a code to calculate the online time by the difference between the 'logintime' and the now time 'time()' and add the result to the 'onlinetime' field. but if the 'logoutime' is not the same as 'lastactive' (that meanse the user is online and making activities in your site because you are tracking him and updating the 'lastactive' field frequently) then write a code to calculate the online time by the difference between the 'lastactive' and now time 'time()' and add the result to the 'onlinetime' field. that way you have the exactly online time logged forever in the 'onlinetime' field! I hope you got me right because the examples will be a lot long of scripts (although I don't mind to share upon request). good luck.
Use the Session ID to keep track of individual sessions.

Categories