PHP知道用户是否在页面上

I am developing a Ticker support client in PHP with CodeIgniter, and I want to know if a user already open a ticket to hide this ticket from the list.

I know there is the solution of change a flag in database when the ticket is opened, then use :

 $(window).unload(function() {
    $.ajax({async:false ..... 
    /* change flag in database */
 });

But, what if the user's navigator is forcing to close ? Do I need a CRON task running to reset these flags ? Do you have some feedback for a complete solution ? Thanks.

Since PHP runs only once per page load, the only way to check continuously if a user is still on the desired page you need Javascript + AJAX. How?

Every 1-5 minutes you update a specific field in the database using the timestamp of the last update (like you said) and in the PHP script you check that field in order to close or keep that ticket open.

By the way notice that this solution requires Javascript enabled so either you force the user to enable it (by blocking it otherwise) or you define that after few minutes (15-1hr) of no page loading you close the ticket.

I can suggest a couple of options.

  • using the ajax solution Jeffrey suggest.

    advantage: easy to implement, supported on all browsers

    disadvantage: not really live

  • using server sent events (similar to the ajax polling solution)

    advantage: less overhead

    disadvantage: not supported on IE & Android, not really live

  • websockets for a completely live solution. Make a connection, on connection lost or closed => release the ticket.

    advantage: live, least overhead

    disadvantage: not supported on <IE10 & Android, harder to implement on the server side.

However for the 'not supported' issues, there are fall-back techniques (modernizr)