The php code below is used with What You See Is What You Get Web Builder, to control a visit counter, and forms part of an extension - created using their Extension Builder. The variables in double $$'s are created in the Extension Builder as a means of easily changing parameters when creating web pages.
The variable $identcookie$ names a permanent cookie on my PC for the website concerned - www.boga.co.uk - but the cookie “first” is created by the php, and should disappear at the end of a session.
The script works fine, inasmuch as the file ‘counter.txt’ is NOT indexed if the computer accessing the website is MY machine (identified using $identname$ or the script is run more than once (if the page is refreshed or returned-to from elsewhere) . Thus only ‘real’ visits are counted.
The puzzle is - despite working as expected - on the first visit to the page, the $revisit variable remains at “NO” - as expected - but the Code Editor in Firefox shows that the ‘first’ cookie EXISTS. I believe that it should not come into being until the second visit.
The code from the Body section of the HTML, which actually displays the visit count is shown below the php - with the $revisit and $user values included for testing. $text$ would contain something like “Visits to BOGA”.
If anyone can throw some light on this puzzle I would be grateful, as these sorts of queries can often hide something else I’ve got wrong.
<?php
//check if first visit
$revisit = "No";
if(isset($_COOKIE["first"]))
{
$revisit = "Yes" ;
}
else
{
$cookie_name = "first";
$cookie_value = "XX";
setcookie($cookie_name, $cookie_value);
}
//check if MY computer
$cookie_name = "$identcookie$";
if(isset($_COOKIE[$cookie_name]))
{
$user = $_COOKIE[$cookie_name];
}
// get the visit count, and update if first visit and NOT on my computer
$file = fopen("$file$", 'r');
$data = fread($file, filesize("$file$"));
fclose($file);
if ($data !== false)
{
$hits = intval($data);
if ($user != "$identname$" && $revisit != "Yes")
{
$hits++;
$file = fopen("$file$", 'w');
flock($file, LOCK_EX);
fwrite($file, $hits);
flock($file, LOCK_UN);
fclose($file);
}
}
?>
HTML
$text$ <?php echo $hits;?><?php echo $revisit;?><?php echo $user;?>