Simple website hit counter (PHP version)

Mushy-pea 1 Tallied Votes 307 Views Share

This snippit is a follow up to my first snippit, namely "Simple website hit counter" which is written in Perl. It does exactly the same thing using PHP. "Boring", you might say? Well, I have my reasons for wanting to learn this language and one needs to start somewhere :) . Also, it will give me a chance to compare how the two languages work for samll programs. If you want to make the counter work on your website you can grab the number tiles from my home page if you like (from the root URL load [0-9]tile.gif). Enjoy.

Steven.

LastMitch commented: Thanks for sharing! +12
<?php

main();

function main() {

$data = "";
access_file("hit_count.txt", $data);

for ($n = 0; $n < strlen($data); $n++) {
$count[$n] = substr($data, $n, 1);
}

for ($n = 0; $n < 4 - strlen($data); $n++) {
echo "<img src=\"0tile.gif\" alt=\"0\">";
}

for ($n = 0; $n < strlen($data); $n++) {
switch ($count[$n]) {
case 0:
$insert = "0";
break;
case 1:
$insert = "1";
break;
case 2:
$insert = "2";
break;
case 3:
$insert = "3";
break;
case 4:
$insert = "4";
break;
case 5:
$insert = "5";
break;
case 6:
$insert = "6";
break;
case 7:
$insert = "7";
break;
case 8:
$insert = "8";
break;
case 9:
$insert = "9";
break;
default:
$insert = "0";
}
echo "<img src=\"" . $insert . "tile.gif\" alt=\"$insert\">";

}

}

function access_file ($filename, &$data) {
$file1 = fopen($filename, "r+") or die ("Unable to open file $filename for read / write.");
$data = fread($file1, filesize($filename));
$new_data = $data + 1;
fseek($file1, 0, SEEK_SET);
fwrite($file1, $new_data);
fclose($file1);

}


?>
Member Avatar for LastMitch
LastMitch

It does exactly the same thing using PHP. "Boring", you might say? Well, I have my reasons for wanting to learn this language and one needs to start somewhere :) . Also, it will give me a chance to compare how the two languages work for samll programs. If you want to make the counter work on your website you can grab the number tiles from my home page if you like (from the root URL load [0-9]tile.gif). Enjoy.

I like the code snippet and like you said it's very simple to learn and follow.

Thanks for sharing!

I attached an image of the results:

1644ab4f20bb4e0548920b2afad571f3

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.