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

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.

Related

Running a function/script per user on the server side

I'm working on a basic lamp(willing to change) website , and I currently need a way to run some function on the server that runs for several hours per user, and every X hours it needs to query the mysql database to see if the value for that user has been updated, if it hasn't it need it to insert a new record in the database...I also should mention that the 'every X hours' can change per user too, and the total runtime of the function per user can also vary.
So basically I need a function that runs continuously on the server for few hours per user. What is the best way to do this? I want the site to be able to support many users (like 10000 +).
I'm willing to try new technologies for every aspect of the site, I'm still in the design phase and I was looking for some input.
I've looked at cron but not really sure how well it would work when dealing with so many users...
edit: Here is a typical scenario of events;
User presses button on the website and closes the browser.
Server starts a timer from when they pressed the button, now
the server will check if that user has pressed a different button within a given time frame (time frame can change per user), say within 30 minutes. If they didn't press the other button then the server needs to automatically insert a new record in the database.
The script will need to continue running, checking every 30 mins for say the next 5 hours.
Thank you!
Cron would work as well as you can code the page it will run. It's not a cron limitation.
The question is ambiguous btw. Maybe explaining your full scenario would help.
Meanwhile, my suggestion would be to set up a scrip that allows you to manually check what you need to check.
You definitely need the DB to be InnoDB optimized with proper indexes to be able to support 1000 plus users.
To alleviate the number of calls to the database, a common practice is to run scripts only on what you are interested (so in the case of users you would only select those who have logged on in say the past 3 hours)
That's achievable in 2 ways, a simple select statement, or by adding entries to a specific table on the login page, and remove them after the automated script has finished running.
All of this is pure theory without understanding exactly what you need to do though.
You are telling what/how you want to do, but not why you want to do it. Maybe letting us know why could lead to a different how ;)
However, what you can do is still use cron (or anything similar). The trick is to have
a last_interaction timestamp column
a maximum_interval column
a daily_runtime column
in your users database. Not optimized but you are in the design phase so you shouldn't pay too much attention to the performance aspect (except is explicitly required).

How to automatically increment a value in database? (LIVE)

I'd love to create great things with number based stuff.
I totally have no idea how / where should I start.
Let's say users have to register then log in to the site to use this feature (already done this).
I tried to save their registration date in timestamp and calculate their value (the one that i need to increment) from the elapsed timestamp since registration. It was working, but when I set a maximum to this value, and then raised it's maximum, it just jumped to the new maximum (since the time was still going). Btw, this thing needs to be working even if the user is completely logged out, and also not on the site. (so it's server sided)
So let's say I need to increment this value by 550 an hour, but after the first hour elapsed the incrementation grows to 650, after the second hour grows to 750 and so on... and as soon as it reached 3272 it must stay there.
It's also important to visually upgrade this value LIVE. So the user doesn't have to refresh the page every time he/she wishes to take a look at their new value. I guess the hard part is that to calculate every second's incrementation value to match the value of the hour. Okay not that hard I guess it must be like 650/60/60 = 1 second
Best Regards,
Henrik
It is not clear what you are trying to do, but you have multiple options.
You can use timestamp itself as a increment value.
Or
You can use cron-jobs. (Google if you need more information about this)
Create a cron to automatically increment your mysql value and set the interval.
Hope this helps.

is it possible to update mysql with timed intervals without a client request

I have working on game where users can send each other challenges. These challenges have timed intervals, say hours, days etc.
When a user logs in the times set can be retrieved through mysql then displayed as a countdown clock using java script to show and countdown remaining time. If the time runs out the database can be updated to display this. This works fine if users are logged in but what if the time set ends when nobody is logged in.
So is there a way of running something constantly on the server to check these countdowns and change the database if the time has ran out or would it work better check the timer when a user views the challenge then act accordingly.
to clarify:
Option 1. Automated script that runs on a server checking the times of each challenge. Either by having a computer constantlylogged in running an ajajar request with an interval timer. (Preferably without a computer and ajax)
Option 2: when a user views the challenge the time is worked out. If the time has ended update this in the database so the challenge now shows up as ended.
If option 1 is possible is it better and how would this Work?
Yes, you can. Use dates. Go with date_created and date_expired. If the current time exceeds the date expired time, etc etc.
are you looking to delete the expired challenges? or set a flag, so the user knows they existed but expired?
depending on your SQL version, look into 'Events'. it's similar to a CRON job, but is run on the SQL server. i would say this is a good option if available to you.

Start a php code (competition in which some users are) for users, logged in or not

Ok I know the title doesn't really tell you what my problem is but I'll try it now.
I am developing a game. People can subscribe their animals for a race. That race starts at a specific time. It is a race for which ALL users can subscribe. So the calculation of which animal is first, second etc. happens in an php file that is executed, every 2mins there is a new calculation for about 1h. So there are 30 calculations. But ofc. this code is not connected to the logged in user. The logged in user can click on the LIVE button to see the current result.
Example: There is a race at 17.00 later today. 15 animals subscribed, from 4 players and they can all check how their animals are doing.
I do not want someone to post me the full code but I want to know how I should let a php code run for about 1 hour (so execute code, sleep 2min, new calculation, sleep 2min and so on) on my server or so. So it is not connected to the user.
I thought about cron jobs but that is really not the solution for this I believe.
Thank you for reading :p
Two approaches:
You use an algorithm which will always come to the same conclusion, regardless of when it is run and who runs it. You just define the starting parameters, then at any time you can calculate the result (or the intermediate result at any point in time between start and finish) when needed. So any user can at any time visit your site and the algorithm will calculate the current standings on the fly from some fixed starting condition.
Alternatively, you keep all data in a central data store and actually update the data in certain intervals; any user can request the current standings at any time and the latest data from the datastore will be used. You will still need an algorithm that has traits of the one described above, since you're likely explicitly not actually running the simulation in real time. Just every x seconds, you run your calculations again, calculating what is supposed to have changed from the last time you ran them.
In essence, any algorithm you use needs this approach. Even a "realtime" program simply keeps looping, changing values little by little from their previous state. The interval between theses changes can be arbitrarily stretched out, to the point where you calculate nothing until it becomes necessary. In the meantime, you just store all the data you need in a database.
Cron jobs are the wright way i think. Check this out when you are not so good with algorithm:How To: PHP with Cron job Maybe you have to use different cron jobs.

Timer based status changes that are saved to database

I have a PHP website using a MySQL database.
We have items that users create, that are on a timer, and once this timer has counted down, without user interaction (basically next time someone sees it) the status needs to have changed.
I'm not sure how to implement this in a way to be accurate to the minute.
So we have an object X, that expires at 10:15pm tommorrow, and the next person to see object X after that time has to see it as expired.
Is the correct way to do this to be the next time object X is loaded we check if it's expired, and if so, update the database?
What happens if 10 people load object X at the same time after it's expired, what's to prevent some sort of race condition from all 10 requests attempting to update the database?
Is there a cron job that runs every minute that I can some how make use of, or any type of timer in MySQL to kick off every minute checking for these and running a script?
I have several ideas on how it -could- be done, like those listed above, but I'm not sure what the most practical is, or what the standard way to do it is as I'm positive someone has solved this problem before.
Is the correct way to do this to be the next time object X is loaded we check if it's expired, and if so, update the database?
Why do you need to update the database? It seems like you might have some redundancy in your DB table - from what you've said, it sounds like you have (for instance) an is_expired column and then an expires_at column.
Why not just get rid of the is_expired column? It's cheap to compare 2 integers, so when you want to determine if something is expired, just fetch the expires_at column and compare with the current time. This avoids any race conditions with expiry, since nothing in the DB changes.
You can do it with cron of course. Or with javascript native function setInterval( "checkFunction()", 10000 ); to alter the db. Or you could use a date field in DB and check for expiration
Make a field date_to_expire as DATE , enter the expiration date and everytime you query for it check to see if the item is expired (this can go up to seconds)

Categories