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 "Date of last visit: "; echo "<br /?>"; echo "Total visits: ".$_SESSION["num_visits"]; $_SESSION["num_visits"]++; } else { echo "This is your first visit"; $_SESSION["num_visits"] = 1; } ?>
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.
But only in some browsers, I found the effect a little inconsistent. I have rewritten it in cookies instead.
$string = "Date of last visit: "; $string .= "<br />"; $string .= "Total visits: ".$_COOKIE["num_visits"]; }else{ $string = "This is your first visit"; } echo $string;
This works a little better!
0 comments:
Post a Comment