Recently after a server crash, I wanted to know which of my sites have the most users online. Knowing that information would help me to determine which site is having the extra traffic, but what is the faster way to do this?
There are several ways to see how many people are browsing your site. In my case I wanted a very fast one that wont produce more overhead to the server, as my server has already been crashed from that traffic peak.
The theory
Php in most cases uses files to store session data. In general those files are stored in the /tmp directory (for unix based servers) and this is defined in the session.save_path php.ini directive.
The cool thing about php is that we can have different directives for each site, so we could use a different directory for each site. This way our site specific directory will hold one file for each session, and without any extra overhead we will be able to know how many people are browsing the site.
In fact this tweak will have better performance, as there will be less files for php to handle, and it is more secure. The last one is because if all sessions are stored in the same directory then it is possible for someone to hijack a session from another domain.
Let's play with the sessions
To do this we will first need to create a directory which will hold the files. The important thing on this is to know the directory path in the filesystem. So if the directory is under our home dir, then we will need to know the path /usr/home/sessions This directory should have write permissions, so to be sure you can chmod it to 755.
Now we need to change some php directives in order to make this work. If your host provides you with a php.ini file for your site, then you should open it and edit it as follows:
Code:
session.save_handler = "files"
session.save_path = "/usr/home/sessions/"
session.auto_start = 1
If php.ini is not an option, then you can create (or edit) an .htaccess file in your web root (document root) and add the following:
Code:
php_value session.save_handler files
php_value session.save_path /usr/home/sessions/
php_value session.auto_start 1
Finally there is a third way to achieve this. Open a php file that is included in your whole web site, and add these lines in the beginning :
Code:
ini_set('session.save_handler', 'files');
ini_set('session.save_path', '/usr/home/sessions/');
ini_set('session.auto_start', 1);
?>
Now that your site has each own session directory, you can easily get the number of online visitors by using something like this :
Code:
echo ((int)count(explode("\n",shell_exec('ls /usr/home/sessions')))) . ' users online';
?>
Tidak ada komentar:
Posting Komentar