I've created a website where users can upload images and i'd like to record the total number of views for an individual image.
Now my idea on the implementation is this:
Store the ipaddress of the visitor in a session, fe:
$key = "view_img_".$img->id;
if(!isset($_SESSION[$key]))
{
$_SESSION[$key] = array();
}
$visitorIpAddress = $_SERVER['REMOTE_ADDRESS'];
$found = false;
foreach($ip in $_SESSION[$key])
{
if($ip == $visitorIpAdress)
{
$found = true; //visitor has visited before in the livespan of this session
break;
}
}
if(!$found)
{
//do sql update query for the number of views for this image
$sql = mysql_query("UPDATE ") //etc.
//Add this ip to the list in the session
$_SESSION[$key][] = $visitorIpAdress;
}
Now my problem is this:
I'd like it to clear a visitor's ipaddress inside the $_SESSION[$key] variable after a certain timelimit to clear resources.
The thing is:
Most of the visitors might only view the image once, and when a certain image gets old it might not be visited any longer, but the session will still exist.
Is there a way to define a lifespan for a specific $_SESSION variable so it resets itself? (equal to $_SESSION[$key] = null)
Or would there be a better way to implement this?
What you are counting via sessions approach is number of unique views. If you just want to count the number of views, don't put too much brain and just run a query like:
UPDATE counttable SET Views = Views + 1 Where ImageID = 123
Populate the ImageID and you're good to go. KISS.
Seems, that you do not understand very clear how PHP sessions work:
So, if you are willing to store number of views in session, you will only be storing views for current user in this particular moment. If you want to store the total number of visits, you need to use the database or another external data storage. For example, your table with images might have views
column and you can increment it after every visit:
UPDATE images SET views = views + 1 WHERE id = 123