Username has left the chat message when his session ends? - php

Basically I have a chat, using AJAX, PHP.
I let guests login by filling their name and clicking login.
It fills the session $_SESSION['guest'].
Now, when they close their browsers, or something, once the session ends, I want it to say in the chat
"The username has left the chat".
But I am not sure on how would I do this.
Any ways to do it? Maybe I could fill an array of users that were active in the past 5 minutes, if not, remove from the array and it will kick them off the chat.
Any ideas?

You could have an array of users in the backend with the timestamp of the last ping.
Then, the clients end can update the backend using ajax by sending a new timestamp every so many seconds.
Whilst your backend is being updated by one of the users, your backend can do a check on all users checking the last timestamp sent to the current time, if its over 2 minutes or something you can tell they have left the chat and output the message.

Without a direct connection to the browser, you won't be able to actively tell if they're connected. I'd suggest a ping-like solution, requiring the browser to ping the server every n seconds to keep the chat "alive".
If the browser doesn't "check in" with the server, the server assumes they've disconnected and reports back to the other participant.
That said, if you're able to dive a little deeper, Google "javascript real-time chat" and you'll have several paths to success.

Add a jQuery .unload() event to your chat client. When they navigate away from the chat it will be fired and you can use it to send the last bit of data to display that message.
Here is the documentation: Link.
Example:
$(window).unload(function() {
//send message to server informing it of client leaving
});

Related

PHP front end user queue

I'm building a site where the users can control a webcam to turn it left and right.
Every user gets one minute of action. There is going to be a queuing system on the site that will allow one by one the users to control the camera.
So my question is the following, does anyone have a suggestion on how to build this queuing system? Are there any tutorials or code I can use?
Thanks a lot!
Have a database table to track the queue for example:
queue (id, session_id, start_time, last_update)
When users hit your page, insert them into the queue table. Use a regular ajax call (perhaps 30 seconds) on the page to poll the server to see if the current users turn is up.
If the user is the first record in the table then it's his turn, so update the start_time to the current time and send your ajax response telling the browser to display the UI with the buttons for the camera movement.
When a button is pressed, verify on the server side that it is infact this users turn and his start_time was < 1min ago, before allowing the action. If his turn is over, delete him from the table so that the next user becomes the first record and gets his turn, then send a response to the browser so that it can hide the camera UI and give a message.
In addition to inserting into the queue on hitting the page, also check to see if the user that is controlling the camera has had his 1min, if so then delete his record (or could be done on the cronjob below).
Each time the ajax poll fires, update the users last_update with a timestamp. Use a cronjob or just on the server side calls to check if any of the records in he queue have a last_update that is older than a short time, e.g. 30 seconds., if any are found then delete them because these are users that are no longer on the page. This will also prevent attackers trying to fill up your queue.
On the same cronjob, check if the user who's turn it is has the start_time populated, if after 30 seconds he hasn't started, delete from the queue.
The ajax calls would make it nice and seamless, but they aren't essential, if the user has Javascript disabled you can still detect that and use a meta refresh of the whole page instead.

I need to show which users are online for my AJAX Chat

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?

Is there a way to limit the number of times per day a user can send a certain type of request?

What I'm doing at the moment is creating a row in a table for each Facebook request that gets sent. Then, every time a user opens up the FB friend picker to send a request I make a call to a php file that requests information from that table and returns with a list of the FB user ids of all the people they have sent a request to in the last 24 hours. I do this for each type of request the user can send.
The issue I'm having at the moment is that if the user initiates a request, sends them off to a number of people, and then immediately opens the FB friend picker again the previous request action's records have not yet all been added to our internal table. Thus, the players, if they go fast enough, can send multiple requests to the same FB friends.
Is there a way, on the FB side, to limit this behavior Or is this entirely up to the developer to constrain? For either case, is there a recommended method by which I should achieve this behavior? Thank you.
Update
It occurred to me that our DB is keeping multiple requests from being entered on a per-user-per-24-hour period. What I do now is simply allow the second request to be made on the FB side and when the code attempts and fails to enter the second row into our DB it makes a FB Graph call that uses the app's auth_token to delete the request from Facebook itself. This means that it will show up for a moment on the receiving player's request page on Facebook but since it isn't linked with a row in the internal DB the user won't receive any reward for clicking-thru anyway.
Thanks for the suggestions, though, everybody. #Gil Birman I went ahead and accepted your answer since it's perfectly valid, even if it's not what I ultimately used to fix the problem. Thanks!
There are several ways to solve the lag problem you mentioned, one way would be to disable your send request button via javascript as soon as it is pressed. In your javascript code, instead of immediately displaying the send request dialog via FB.UI, send a json request to your server. Only when the server responds should you display the fb send request dialog. Also, the response that the server sends should include the list of friends to exclude. After the fb request is sent your javascript code should send one more json request to the server to indicate what rows in the database needs to be updated. Only when the server responds this second time should you finally re-enable your send request button.
However, there is no way to actually limit the # number of requests that your user can send. That is, no matter how well you design your javascript/php code, your user could still theoretically invoke the request dialog via the Javascript console to completely bypass your attempts to secure the app.

How to update content based on user actions [like the facebook wall]

For my next application i would like to implement something that has a feature like the facebook wall but let me explain a bit. For those of you who used facebook you know that when somebody posts a message on your wall, and you are logged in to your account, you will get a notification immediately somewhere in the lower left corner. Lately they even pushed this a little bit further and if somebody comments on it the comments are updated as you visualize the page, it's like an instant chat.
My application will be developed in PHP, I will use Zend Framework to do it. I'm interested in the basic principle that makes the facebook wall behave like that (updates in real time). I know there is ajax involved but I can't really tell how is the javascript triggered when the user is doing something. Or even more, how to push back to a user some info that was added after he viewed the page. For example, let's say that a somebody adds me as a friend. I would like to see a notification saying "X has added you as a friend" if i am logged in. I hope you understand what I'm trying to do.
If you can tell me some basic ideas, maybe provide some links that have this information I would be very grateful.
Thank you for your time in reading this.
you need to look at comet , reverse ajax , ajax polling
If some event is triggered, then store the event on database (with ajax or without ajax).
You will be needing a script in server to check if some event has been triggered or not. This script should be able to check events that are stored in database.
You need to execute script in step 2 periodically. This can be acheived with with ajax (javascript or jquery) and a function settimeout (on javascript) to send ajax request to server periodically.
Changes are sent from server. So parse the response and update in page using javascipt and jquery.
So, it can be summarized as
Register an event (for one user)
Check the event (for other user)
Parse the response and update the page
There are several elegant ways to do this as answered by others.
The best would be the start the project and ask for help where ever stuck.
It is only partially possible to keep an HTTP connection open, so the best option is probably to poll for changes. You can send a request each second to see if anything is changed since time 'x'. On each response you send along the server time. With the new request you send the time of the old request and the server can return any events that happened inbetween.
Also you can read something about AMQP. You can send a message to recepients inboxes (after some actions in your system) and then read inboxes after start or with some time interval.

Log what page the user is currently on

I have a chatroom on my website. I want to compile a list of online users in the chatroom.
What is the best way to do this?
Would it be to log the last page the user visited and if it was that page, they are in the chatroom?
What different techniques can be used to do this?
Thanks
If you're using Comet in your chat application, then you'll have a channel open to the server, which would be bound to the client side as an open HTTP request.
As long as that request is open, the user is in the room. If the request closes, then the user is no longer in the room.
I would use sessions javascript library to record each page the user has visited and then retrieve those values in your chat client via javascript.
include the library on each page.
in the sessvars object, make an array sessvars.visited = []; [if sessvars.visited is not already an array]
Now on each page do something like this sessvars.visited[] = location.href
On the chat client page, use javascript to iterate through sessvars.visited to obtain all the URLs. For example, To list out the URLs in HTML w/ Jquery do the following:
var urlList = '';
$.each(sessvars.visited, function(key, value){
urlList += value + '<br />';
})
Note: Sessvars is an alternative to Cookies that has a very large capacity (10mb in most browsers). However, session data is only available in an active window. Information is lost once the window is closed, and as far as I know cannot be queried from other windows. So if chat is open in a different window than they were browsing in, this will not work.
You should make a javascript request to the server every x seconds.
You already have to do this (for retrieving the ongoing chat conversation and the list of users participating).
On the server side you know what users are on because of this request. You just have to log these requests.
Yshout works by doing an AJAX request against yshout/yshout.php every 6 seconds. Add a bit of code to yshout.php to track how many unique users it's seen in the last 10 seconds, and you should be set.
Edit: you want the names of everyone active in the chatroom? I'd be tempted to add a database table for this - every time they hit yshout.php, add a name+timestamp entry and delete all entries more than 10 seconds old. Then query with GROUP BY name to get unique users.
Edit 2: The chat client already does an AJAX request on yshout.php every six seconds. All you have to do is add a snippet of PHP code inside the 'if (isset($_POST['reqFor']))' clause (the bit that responds to the AJAX requests).
Keep it brief! Remember, it's going to get hammered on something like 150 times per minute.

Categories