简体   繁体   中英

Check if a user is online, Codeigniter framework

I want to add online or offline feature in my website, who's built on PHP Codeigniter framework.

I found this library OnlineUsers0.2 . But, I'm already using built-in session class and I want to take advantage of it on online usears too.

My idea is to insert an other field in ci_sessions table that has user id, and when I display user's information I do a check to that table based on user id if it's exist on ci_sessions table and last_activity is less than 5 minutes than the user is online and if it's not exist or last_activity is more than 5 minutes than the user is offline.

So, my first question here is how can I add that user_id field to ci_sessions table and is it a good way to do that.

And my second question is there a better way to do what I'm looking for?

Answering your second question, you can use javascript websockets easily for doing this in real time. You can also you long polling using the same logic but its not a good approach if you have many users of your application.

Real Time Online function Just create a column 'is_online' in your users table and write a function to update the is_online status flag in the database.

Create your websockets php server using http://socketo.me/ or https://github.com/nekudo/php-websocket . Here your server logic will reside ie if user comes online update the online flag and vice versa.

In javascript using websockets, you can simply hook onopen and onclose event to do trigger server side functions. As the user hits any of your page simply update the status in database.

function WebSocketTest()
{
         if ("WebSocket" in window)
         {
              alert("WebSocket is supported by your Browser!");

              // Let us open a web socket
              var ws = new WebSocket("ws://localhost:9998/echo");
              ws.onopen = function()
              {
                  // Web Socket is connected, send data using send()
                  ws.send("Message to send");
                  alert("Message is sent...");
              };
              ws.onclose = function()
              { 
              // websocket is closed.
              alert("Connection is closed..."); 
         };
    }
    else
    {
        // The browser doesn't support WebSocket
        alert("WebSocket NOT supported by your Browser!");
    }
}

Further Reference http://www.tutorialspoint.com/html5/html5_websocket.htm

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM