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


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.

  1. <?php session_start();
  3. if ( isset($_SESSION["last_visit"]) ) {
  4. echo "Date of last visit: ";
  5. echo date("j F Y, H:i:s", $_SESSION["last_visit"]);
  6. echo "<br /?>";
  7. echo "Total visits: ".$_SESSION["num_visits"];
  8. $_SESSION["num_visits"]++;
  9. } else {
  10. echo "This is your first visit";
  11. $_SESSION["num_visits"] = 1;
  12. }
  14. $_SESSION["last_visit"] = time();
  15. ?>

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.


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)

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.
  1. if(isset($_COOKIE["last_visit"])){
  2.  $string = "Date of last visit: ";
  3.  $string .= date("j F Y, H:i:s",$_COOKIE["last_visit"]);
  4.  $string .= "<br />";
  5.  $string .= "Total visits: ".$_COOKIE["num_visits"];
  6.  setcookie("num_visits",$_COOKIE["num_visits"]+1,time()+100000);
  7. }else{
  8.  $string = "This is your first visit";
  9.  setcookie("num_visits",1,time()+100000);
  10. }
  11.  setcookie("visit",time(),time()+100000);
  12.  echo $string;
This works a little better!

Add new comment

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