How do I count logins

I'd like to calculate how many days a user logs in, and also consecutive days logged in. It seems straightforward to catch the login event and count from there. What if the user does not log out? Will the login event always get triggered?

  • no, the login event is only triggered when they actually authenticate.  If the session persists over multiple days you'll be missing days they were on.

    You could just use your init function:

     

    //pseudo code

    if(elgg_is_logged_in() && !has_login_been_recorded_for_today()){

        record_login();

    }

     

    This will work, the downside is that it triggers on every pageload, so there will be some overhead.  Right now though I can't think of a better way, maybe someone else can improve this.

  • @Matt: i think the overhead for one single if-statement is insignifcant. Also.. this can be done in  "system", "shutdown" - so the user wont notice anything.

  • it's not the overhead of the if statement, presumably the has_login_been_recorded_for_today involves checking the date against the existance of some metadata or annotations.  It's not a lot, just some extra queries that are wasted 99% of the time.  I was just wondering if there was a more efficient way.  Probably not though.

  • @Matt : why cant a cookie be created during the record()? If no cookie existis do_record(). So this wont add extra db calls and processing also elgg clears all the session details when logout is made. .

  • Yup, that's the answer.  Listen to webgalli  :)

  • For the record, if you use the system, shutdown event PHP still won't close the connection until it's done processing. That hook isn't very useful.

  • Thanks guys. I've implemented a solution using a cookie. I'm wondering how to extend it for users who log in using different computers. Should I save the cookie data as ElggUser metadata and then use $_COOKIE['Elgg'] to determine that a different session has started?

    The likeliest scenario is that classroom students log in during the day using a publicly available PC, then maybe log in at home on their home PC at night or weekend.

  • The cookie method is just to put a wrap around the above function mentioned by Matt. The actual tracking should be done through Elgg metadata / annotation. Because users can remove cookies in the browsers and this will give false counts if you stick to it. also the problem of login from different computers.

  • Ah okay. So I just use the cookie to avoid looking at metadata.