I would suggest using a persisting cookie to store visitor information.
Tracking returning visitors
When a visitor comes to your site, you could check if they already have a visitor_id cookie in their browser:
- If they do not, create a visitor ID for them and save it in a cookie, then use AJAX to send the ID to your server and create a new visitor from it in the database.
- If they do, you can simply query your server via AJAX to get previous visitor information, or append their current session to their previous visits. More on this below.
This way you can track individual users by identifying the browser they're visiting from, as that's more likely to be stable than their IP or any other anonymous identification.
Note: you can also do it purely using PHP's $_COOKIE without AJAX, but I find it more comfortable to completely separate the client-side code from the back-end. It is only a matter of personal preference.
Some front-end pseudocode for this
if (haveVisitorCookie) {
getVisitorDataByID(visitorCookie); //some ajax implementation
} else {
createVisitorCookie(); //save to back-end
}
Tracking user activity on the site
The above part only covers identifying new/returning visitors and persisting visitor information. To record what a user does in a single visit, the easiest way is to use PHP's built-in sessions.
All you need to do is call session_start()
at the beginning of your code and your visitor is assigned a session that will remain open until the visitor remains on any page of your site. You can then add data to the current session with the magic $_SESSION
variable. You can store any data in it in the form of $_SESSION['key'] = value
.
For example, you could query the current session ID on each page load, and if it already exists append the current action to it, otherwise save as a new visit from the same visitor.
Some back-end pseudocode
session_start();
if ($visitorID) { //visitorID is sent from your front-end and contains the cookie data
$previousSession = getLastVisitorSession($visitorID);
$currentSession = session_id();
if ($previousSession) {
if ($previousSession === $currentSession) {
// New pageview on same session
} else {
// New session
...
saveNewVisitorSession($visitorID, $currentSession)
}
}
}
Bonus points: you can even help your users continue from where they left off by loading their last session in case they don't have a current session ID but have a visitor ID with a previous session stored
Hope this helps!