Hi all,

I am trying to make a script for maximal hit counter using below codes. So if user hit for bigger than 2, it would re assign the file of hitcounter.txt into "0" (as if in resetting) .. I tried this code but it does not work

<?php

//database SQL
$count_my_page = ("hitcounter.txt");
$hits = file($count_my_page);
$hits[0] ++;
$fp = fopen($count_my_page , "w");
fputs($fp , "$hits[0]");
fclose($fp);
//echo $hits[0];

if ($hits[0] =='1')
{
echo "1";
}

if ($hits[0] =='2')
{
echo "2";
}


if($hits[0] !='1'|$hits[0] !='2')
{
$hits[0] = '0';
}

Thank you for the tips

Hi,

You are only using a single pipe symbol (|) when you should use 2.

Your current statement reads (if hits is not 1 OR hits is not 2) so only one of the conditions needs to be met and your counter will reset (if the counter is 1 it will match the "is not 2" part, if the counter is 2 it will match the "is not 1" part.

Try changing this

if($hits[0] !='1'|$hits[0] !='2')

to this

if($hits[0] != '1' && $hits[0] != '2')

This reads (if hits is not 1 AND hits is not 2) which will give you the result you expect.


Zagga

Hi thank you for the response,

but if I change it to &&, the value inside the text (hitcounter.txt) does not go to "0", but still in current change. Or is it not possible to change it programmitically?

Hi,

How about the following...

<?php
// Define hits count and hit counter file
$intHits = 0;
$strCountFile = 'hit_counter.txt';

// Get existing hits count from file, if file exists
if(file_exists($strCountFile) && is_readable($strCountFile)) {
    $intHits = (int)file_get_contents($strCountFile);
}

// Echo hits
echo $intHits;

// Increment hits - this will iterate through 0, 1, 2, 0, 1, 2
$intHits = ($intHits += 1) % 3;

// Write hits to file
file_put_contents($strCountFile, $intHits);
?>

Does this do what you want??

R.

Hi!

Sorry, I did not reply that soon! but your logic works superbly.. thank you!