I found this script in php which counts button clicks and saves them to a txt file.
<?php
if( isset($_POST['clicks']) )
{
clickInc();
}
function clickInc()
{
$count = ("clickcount.txt");
$clicks = file($count);
$clicks[0]++;
$fp = fopen($count, "w") or die("Can't open file");
fputs($fp, "$clicks[0]");
fclose($fp);
echo $clicks[0];
}
?>
<html>
<head>
<title>button count</title>
</head>
<body>
<form action="<?php $_SERVER['PHP_SELF']; ?>" method="post">
<input type="submit" value="click me!" name="clicks">
</form>
</body>
</html>
what i cant figure out is how to echo the number of button clicks to a different part of the html. i've tried placing:
<?php
echo $clicks[0];
?>
but that does not work. what am i doing wrong? thanks..
I'd suggest separating the part of the code that reads the click count from the part that increments it, so that you can call each part on it's own. Then you don't have to save the click count from the actual incrementation part; you could get the click count on it's own whenever needed, exactly as it exists in the file at that point in time.
if( isset($_POST['clicks']) ) {
incrementClickCount();
}
function getClickCount()
{
return (int)file_get_contents("clickcount.txt");
}
function incrementClickCount()
{
$count = getClickCount() + 1;
file_put_contents("clickcount.txt", $count);
}
With that, you could include the current count at any point in your HTML, by calling the getClickCount function.
<div>Click Count: <?php echo getClickCount(); ?></div>
</body>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With