Problem with script counter.php

All I mean by that is to add echo statements so you can see each bit of code as it’s being executed. For example, in the start of your code:

<?php
session_start();
$debug = true; // Change this to false when you want to stop the extra echos
$counter_name = "counter.txt";
// Check if a text file exists. If not create one and initialize it to zero.
if (!file_exists($counter_name)) {
  if ($debug) echo "Counter file did not exist";    // ** DEBUG 
  $f = fopen($counter_name, "w");
  fwrite($f,"0");
  fclose($f);
}
// Read the current value of our counter file
$f = fopen($counter_name,"r");
$counterVal = fread($f, filesize($counter_name));
fclose($f);
if ($debug) echo "Counter value is " . $counterVal; // ** DEBUG
// Has visitor been counted in this session?
// If not, increase counter value by one
if(!isset($_SESSION['hasVisited'])){
  $_SESSION['hasVisited']="yes";
  $counterVal++;
  $f = fopen($counter_name, "w");
  fwrite($f, $counterVal);
  fclose($f); 
  if ($debug) echo "Incremented counter"; // ** DEBUG
}
...

So I’ve added the lines that end in “** DEBUG” as a comment, which will echo whichever ones work. Once you’ve figured out the problem, you can stop them outputting by changing the line at the top to set $debug to false instead of true.

2 Likes