Using PHP Sessions To Detect Returning Users

3rd February 2008 - 2 minutes read time

To detect a user returning to a web page you can use the built in PHP session manager. At the start of the code you can use the session_start() function to initiate the session, you can then use the $_SESSION global array to store and retrieve information. The session_start() function sends a cookie to the client with a unique code that looks like this

8a9af5644326881594811db6fe96faf8

The session variable information is kept in a file on the web server and when the session_start() function is called PHP looks for the file with the corresponding name. It then parses this file and loads the variables into memory. This is all done behind the scenes by PHP, all you need to know is that you can set values in the $_SESSION array and get them back the next time the page is loaded.

";
    echo "Total visits: ".$_SESSION["num_visits"];
    $_SESSION["num_visits"]++;
  } else {
    echo "This is your first visit";
    $_SESSION["num_visits"] = 1;
  }
    
  $_SESSION["last_visit"] = time();
?>

The two pieces of information stored here are last_visit and num_visits. The code checks to see if the last_visit variable is set, if it is then the user has visited before so the code can increment the num_visits variable. If last_visit isn't set then the user has not visited before and so the value is set to 1. The last_visit variable is always set at the end of the code as this isn't specific to the number of times a user has visited.

Comments

Permalink
Forgive me if I am wrong, but don't sessions expire when the browser is closed. Thus showing no one will ever be returning visitors as they will be assigned a new session_id? There is ofcourse exceptions such as using Firefox's built in session manager. I believe the best option to be a blend of cookies and IP address to find returning customers, but even then the data is so jaded its not worth accounting for... But, good work on all you other snippets.

Jamie (Thu, 06/19/2008 - 09:44)

Permalink
You are quite right, if the browser closes then the session is thrown away. But only in some browsers, I found the effect a little inconsistent. I have rewritten it in cookies instead.
if(isset($_COOKIE["last_visit"])){
 $string = "Date of last visit: ";
 $string .= date("j F Y, H:i:s",$_COOKIE["last_visit"]);
 $string .= "<br />";
 $string .= "Total visits: ".$_COOKIE["num_visits"];
 setcookie("num_visits",$_COOKIE["num_visits"]+1,time()+100000);
}else{
 $string = "This is your first visit";
 setcookie("num_visits",1,time()+100000);
}
 setcookie("visit",time(),time()+100000);
 echo $string;
This works a little better!

Add new comment

The content of this field is kept private and will not be shown publicly.