tags:

views:

304

answers:

1

Hi, I use a simple MySQL table to count day hits for specific pages/items in a website. Using 'id' column for page/item ids, 'date' for the day of the visits/hits, and 'hits' column for the number of hits.

Everytime someone visit the page the value of hits for that specific date is updated to +1.

But, the value is updated one more time each time the page is refreshed or revisited and I need a way to save the page ID in a cookie or the visitor IP in the database to update the hits just one time.

I never worked with cookies so I dont really know how to do it and the limitations of the data than can be stored in a cookie.

I think saving the IP adresses of the visitors in the database is a really waste of queires and bandwitch and I read that its not always possible to get the real IP and this can make some problems and some hits not updated.

I also read that its better not to use GLOBAL variables too much...

Can someone please explain me the best way to do it and how to do it??

Thanks!

+1  A: 

If you'd rather deal with cookies as PHP variables, something you are very familiar with most likely, I'd use a session.

session_start()
$page = 1; // Page ID
if(isset($_SESSION[$page]))
{
    // Do something if the person refreshed
}
else
{
     $_SESSION[$page] = time();
     // record hit.
}

Get the Page ID in the $page variable, and it will save it in a session. A session is like a cookie, except it is saved on the server side.

Basically, if there is a variable with the ID of that page, it will do nothing, else it records a hit and sets the variable.

You can check this tutorial for more on sessions: http://www.tizag.com/phpT/phpsessions.php

Like cookies, Sessions will only last for a certain amount of time. So it will record a visit after a few days.

You might even want to , manually check to see when the last time visited was. If it is over an hour, record a new hit, because they probably aren't just refreshing.

Chacha102