PHPCOUNTER, some additions to the original code …

What we needed

PHPCounter is a simple but comfortable web hit counter with a lot of useful statistics information developed using PHP language. It can track different web pages inside any HTTP Server and stores all what it gathers inside a mySQL database. That was fine, but we were in need of adding some functionalities so as to put it into production status.

Granting or denying counters access by IP Address

By default, all counters previously created and enabled  inside PHPCounter can be accessed by everyone who wants. Thus, we needed a trivial control over those IP addresses trying to get access to the counters’ list and, of course, to the specific counter statistics page. In order to do so,  I’ve added some code lines to the original source code structure so as to allow trivial checks for any connecting IP Address.

All code changes have been made in the source file index.php.

The code is shown below:

$rs = fopen("/etc/phpcounter-secs.conf", "r");
	$allowed = false;
		// Iterate all over the lines looking for this IP ...
			$line_data = fgets($rs);
			// Process this line if it's not a commented one !!!!
				$flds = explode("t", $line_data);
				$flds[1] = trim($flds[1]);
				// If there are valid data, get the ip ...:
				if($_SERVER['REMOTE_ADDR'] == $flds[0]){
					// Okay, in case of "ALL" entry, allow this ip ...
					/* Are the user trying to view counter statistics ? */
						// If there are a list of counters ... :
						$counters_list = explode(",",$flds[1]);
						for($ic=0; $ic<count($counters_list); $ic++){
							// Check if the user is trying to access any valid counter
							// inside its own list:
								$allowed=true; break;
		} fclose($rs);
		/* Now, grant the access or not ... */
		if(!$allowed){echo file_get_contents("../errors/404.htm"); return;}
	}else {echo file_get_contents("../errors/404.htm"); return;}	/* There's no file, abort : */

The configuration file format

The configuration file is stored in /etc folder, so that it’s outside the website publication directories. Its syntax is quite easy to understand:

#   IP  <tab>   ALL|counter-name1,counter-name2,…,counter-nameN <r>
#   Lines starting with “#” are not processed.

In order to get the counters’ list, any IP must be present right in this configuration file with the keyword “ALL“.

The keyword “counter-name1, counter-name2, …, counter-nameN is refered to the name field for any desired counter previously inserted inside the mySQL database.