This article mainly introduces the code for counting the number of online website users implemented by php + memcache. The code example is concise and practical. For more information, see
This article mainly introduces the code for counting the number of online website users implemented by php + memcache. The code example is concise and practical. For more information, see
I want to show the number of online users in my blog statistics. I have found many examples on the Internet, such as database storage data or file storage, and the code looks too complex.
When I came back in the evening, I thought about it. I saw the Memcache service installed on my server. Why not use Memcache.
The implementation process is as follows:
:
Implementation Code:
<? Php $ mc = new Memcache (); // connect to memcache $ mc-> connect ("127.0.0.1", 11211 ); // get online user IP address and online time data $ online_members = $ mc-> get ('Online _ members '); // if it is null, initialize the data if (! $ Online_members) {$ online_members = array ();} // obtain the user ip address $ ip = $ _ SERVER ["REMOTE_ADDR"]; // reset the online time for the access user $ online_members [$ ip] = time (); foreach ($ online_members as $ k => $ v) {// if the page is not accessed after three minutes, it will be deemed as expired if (time ()-$ v> 180) {unset ($ online_members [$ k]);} // reset the online user data $ mc-> set ('Online _ members ', $ online_members ); // obtain online user data again $ online_members = $ mc-> get ('Online _ members '); // input echo count ($ onli Ne_members);?>