I have an Ajax which sends username/id to PHP every second in order to know which user is currently online.
PHP then takes the user id and updates it's field in an activity table with the current time for the given user.
Is this approach correct, because it uses a lot of CPU from my current hosting plan (and that's just for one session)?
Instead of continuously sending data to the server, update the activity for a given user upon navigation. This approach comes with advantages.
It will be gentle on system resources
It will be easy for you to track whether a user is active or not
Related
I am currently working on a Javascript multiplayer game.
When users want to play, they enter a waiting room where they wait for players to play with.
It is stored in a SQL database this way :
I have a table named USER with some data on the players, and another table named WAITINGROOM which associates the id USERID of the user waiting for a game with other infos.
When players leave the waiting room or close their browser, I delete the row with their id in table WAITINGROOM.
But let's suppose the user loses his internet connection while looking for a game. How can I know he is offline so I can remove the row containing his id ?
The player is offline so it is definitely not client side I can deal with this.
Maybe server side in PHP ? Or directly in the database using timeouts or something...
I assume you have a script (probably called via ajax) which fetches the online users for the current user. Simply add a column like 'last_seen_online' with a timestamp. Update the field every time the user calls this script. Now you can filter it in your sql for example get all users which have been online during the last minute. - Everything not active since one minute is considered offline like this.
To get rid of users which went offline you can implement a garbage collection(like php with sessions does). You grab all users which havent been seen since the last (for example)5 minutes. You place this garbage collection in the same script. To keep the load low. You dont call it every time, just like 50% of the time with if(rand(1,100) > 50) or any percentage you like.
I've created an iOS and android app that uses a database where users can login which in my case "User_active" gets changes to 1 and logged out gets changed to 0. The only problem I have is that I cannot check to see if the user has left the app, or if they have closed it, so what I want to do is create an event on phpmyadmin to change the "User_active" to 0 after 30min, but I can't seam to get things right. I'm using Awardspace as my host and I've only seen tutorials for localhost. Errors that I'm getting are that my user account does not have the write privileges to create the events and I cannot find any user tabs to change user privileges. If anyone can send me off in the right direction that would be great or even better a solution.
phpMyAdmin is a fantastic interactive tool, but it is not the tool for this.
In some ways, this is a fairly common problem. Typical web based applications don't know when a user has left, they only know when a user does something. One method is to do the following:
1 - Add a field to the user table (the same table that has the "user_active" field) to track the last activity by that user of any type. This should be a DATETIME or TIMESTAMP field and updated always with the current time.
2 - Add a cronjob to check any records in the user table to see if they are (a) still logged in (user_active=1) and the timestamp is more than 30 minutes old. If so, set user_active to 0 - essentially force a logout after 30 minutes. You may want to have an additional field to indicate it was a forced automatic logout rather than a user-initiated logout.
If your hosting service allows cronjobs, then run this periodically (perhaps every 5 minutes) and you are done. If your hosting service doesn't allow cronjobs then one option is to add a call to the "automatic user logout" function as part of every regular page. That won't work if you have thousands of active users as the overhead would be too much (and the delay on each page display). But if you have a small number of active users it will get the job done - I have done plenty of system housekeeping using that method.
I am building a link directory style web application. For simplicity all of the following are examples. On my website I have 10 categories. Each category has it's own page and each page has 100 links in a table format. Each link has many columns like name, id, url, etc but the focus of this question deals with the "time last viewed" column. It will display a default text if the user/visitor has never clicked the link however if the link has been clicked by the user prior to the visit it will display the time/date the user last visited that link.
The way I have it set up is when the user clicks the link they are sent to another page/script (using GET method. link 1 is appended with ?rid=1) I use a switch contruct. (Case value is 1 from $_GET execute code block) this code block is where i need the user statistics caputuring to happen. Once the function runs and both captures and stores the visit statistics info the user is sent to the requested resource via header location. So the next time to user sees the list of links on the category page the link they visited will now display the time they visited it.
On my production site i have up to 1000 links. If they clicked each link it would say next to each link the last time they clicked it. Important to include users will be logged in when clicking each link.
How would you go about doing this? Store the info in a cookie or in the database? As there are 1000 links there could be 1000 different values. Thanks in advance.
It isn't a lot of data so you can do both, store in the database as well as store in a cookie. Ideally for performance, you should retrieve from the cookie first and then retrieve from the database if the cookie doesn't contain any user information pertaining to that link. Depending on your performance requirements and the amount of traffic you anticipate, you can use database storage, in-memory storage and asynchronous updates.
database updates are instant but can impact overall performance and page load times
in-memory caching such as apc gives best performance but data needs to be synchronised to the database
asynchronous updates are great for balancing out performance hits because you can register a view from the client side using JavaScript after the page has loaded, rather than during php execution on server side.
Personally I would use all 3 if possible because it gives a good platform for future development.
I have an inline chat application which I got from Ajax Chat, which is working brilliantly. The application allows a user to chat with users that are registered on the system. Ie:
Now I need to show if the user is online or offline.
So my question is how do I show online users using PHP?
Thank You
Basically what you need is a way to register users activity.
One way you can do this is doing it by sessions within PHP, and you log these. There are tons of ways to register then your activity in a log. If the activity is not updated for example in 5 minutes, the user is offline. Bassically you just need then a sessionId, and a timestamp (and i would recommend this also to hang to a userid). If offline, there is no userId assigned and when online you add a userId. If you have those, its pretty easy. Its a matter of updating them constantly when a new page is loaded and if they log out, you simply destroy the session, or update it so it wont be linked to the user.
It may not be the best system, but it works, and it might help you.
I don't know your specific needs. Pardon me, If I am wrong.
If Jabber support is there with Ajax Chat, why not try ejabberd kind of XMPP servers rather than re-inventing the wheels on your own. And you could have a look at Apache Vysper too, since it has support of extension modules too. If XMPP server is there, users presence handling and message transfer would become a cake walk.
What you need is a constantly update for a table in your database that save the last change in an user and save the date time... so if that date is more than 5 or 10 min, the user ir off..you can do it with ajax...
What i would do is have a script that the clients run to do an ajax call to update a entry in your database with a time stamp for last seen. Not too often or you will overload your server.
you can also put some if statements where it checks for keystrokes, mouse movement, and if the window is active if you really want to get technical and do a away status.
then in active chats just check the time stamp for active messages or when the user list is open. anything outside a acceptable range will show the user as off line. 5 minutes seems pretty long to me. poll for a check every 10 seconds maybe?
I'm not awesome enough to write a chat application, and I'm trying to get one to work, and I've recently downloaded one from here, it's pretty good so far, as I've tested it out on XAMPP, but I have a slight problem. I'm trying to generate a list of online users to give it a more practical application-like feel, but the problem with that, is I have no clue how to do it easily.
When users login to my site, a session named g_username is created, (the chat says 'username', but I'll fix that) and from what I see so far, the easiest method would be to store their username in a database called OnlineUsers and call that data via Ajax, but, the other problem, is that it's session based, and sometimes the users can just leave, without logging out, and I intended to run a script to logout the user from both the OnlineUsers table, and by deleting the session.
If they leave without logging out, they'd be online forever! I could potentially suffix a bit of code on every page, that toggled an ajax event on page close, the event being a script that kills their OnlineUsers table record, but then again, that would load the server with useless queries as users jump between pages, as far as I'm aware.
Creating my entire site in Ajax isn't really an option, as it's a load of different sites combined in to 1 'place' with a social 'layer' (if you will) from a social service.
Does anyone see a way to do this that would make sense, and be easy to integrate, and do with Apache, without command line access?
You could so something like storing a timestamp of the users last action in a database, comparing that timestamp when outputting online users and making sure that it was done at most 1 min ago.
Run on all/vital pages:
(Deciding if the last action is outdated, you could also check if it was done for one minute ago to reduce the database-load)
if($user['lastAction'] < time()) {
//update into database, last action is outdated
}
When calculating the amount of users online and is within the loop of each timestamp
//If the users last action was within a minute, the user is most likely online
if(($row['lastAction']- time()) > 60*60)
//count user as online
you could have a cron job [if you have cpanel] running on the server once every 60secs or so, that checks when a user last sent anything via the chat if they have not in the last lets say 5mins then remove their entry from the online users list.