Code for counting the number of online website users implemented by php + memcache

Source: Internet
Author: User
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);?>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.