colindunn
colindunn

Reputation: 3163

Simple PHP hit counter / if else statement

I am trying to create a hit counter that once it reaches a certain number (in this case, 5), it will no longer display the amount of hits. This is my code:

<?php
$count = ("hits.txt");
$hits = file($count);
$hits[0] ++;
$fp = fopen($count , "w");
fputs($fp , "$hits[0]");
fclose($fp);

if ($hits > 5) {
    echo "More than 5 hits";
    }

else {
    echo $hits[0];
    }

?>

What am I doing wrong?

Upvotes: 1

Views: 519

Answers (3)

Michael Krelin - hacker
Michael Krelin - hacker

Reputation: 143099

More or less everything. In addition to other answers this

fputs($fp , "$hits[0]");

won't work as expected, you want either "{$hits[0]}" or $hits[0] (no quotes).

That is, if you don't care about concurrent access.

Upvotes: 0

Jon
Jon

Reputation: 437386

You are overcomplicating things. It would be much easier to do it like this:

$hits = file_get_contents('hits.txt');
++$hits;
file_put_contents('hits.txt', $hits);

if($hits > 5) {
    echo 'Over 5!';
}
// else etc

As for your current code, the problem is that you don't test the number of hits with the correct syntax $hits[0] -- which you already use in fputs -- but with the wrong $hits instead. Remember that due to the way file works, $hits itself is an array. PHP will happily let you compare an array to an integer, and there are rules that define how the comparison works, but don't go there.

Upvotes: 6

Michael Berkowski
Michael Berkowski

Reputation: 270637

You need $hits[0] > 5:

if ($hits[0] > 5) {
  echo "More than 5 hits";
}

The array value $hits when compared against a number 5 is compared as the string Array rather than the value of the array's first item. The string Array is always greater than 5.

Upvotes: 3

Related Questions