PHP session_save_path() vs Shared Hosting
I am re-posting this question since I did not get any useful answers the first time.
I have a simple session counter on my site utilizing session_save_path(). The code does not work in a shared hosting environment because it returns a count of all sessions on the server for all sites - or so I presume.
Could someone tell me how I can modify this so it works properly. I know counting sessions does not accurately reflect the numbers but it does not have to be a 100% accurate. I also do not think that hitting the database is a smart idea for a simple function like this.
There has got to be a way to implement this the right way. Can you help?
Thank you!
<?php
//------------------------------------------------------------
// VISITORS ONLINE COUNTER
//------------------------------------------------------------
if (!isset($_SESSION)) {
session_start();
}
function visitorsOnline()
{
$session_path = session_save_path();
$visitors = 0;
$handle = opendir($session_path);
while(( $file = readdir($handle) ) != false)
{
if($file != "." && $file != "..")
{
if(preg_match('/^sess/', $file))
{
$visitors++;
}
}
}
开发者_JAVA百科 return $visitors;
}
?>
You could set a different session path for your application. That's also a good idea to prevent others to get your session data.
However I think using a database for this is a smaller hit on the server then reading the session directory :)
You could use a heap memory table that would work without any disk access.
You might be able to tell "your" session files apart from those of other users using fileowner()
or is_readable()
- the latter following the logic that you will have only access to your session files (well, hopefully!)
This will heavily depend on the server configuration, if it works at all.
The only really good way that comes to my mind is to have your scripts write into a separate database table for each session, frequently clean up old records, get the count from there.
I recommend to use a .txt file to save the counts.
Example:
<?php
/**
* Create an empty text file called counterlog.txt and
* upload to the same directory as the page you want to
* count hits for.
*
* Add this line of code on your page:
* <?php include "text_file_hit_counter.php"; ?>
*/
// Open the file for reading
$fp = fopen("counterlog.txt", "r");
// Get the existing count
$count = fread($fp, 1024);
// Close the file
fclose($fp);
// Add 1 to the existing count
$count = $count + 1;
// Display the number of hits
// If you don't want to display it, comment out this line
echo "<p>Page views:" . $count . "</p>";
// Reopen the file and erase the contents
$fp = fopen("counterlog.txt", "w");
// Write the new count to the file
fwrite($fp, $count);
// Close the file
fclose($fp);
?>
Source: http://www.totallyphp.co.uk/scripts/text_file_hit_counter.htm
Best,
Alex.
精彩评论