Friday, May 24, 2013

A button hit counter for your PHP website.

In this tutorial, i'm going to share how to make a button hit counter, it's a basic level PHP so many can understand it and modify it. For this tutorial i'm going to save the counts in a text file, but if you want you can store it in a database.


PHP:  
<?php
$file = "data.txt"; // Giving a name to our text file which will store numbers of counts
if(!file_exists($file)){// Checking wether file data.txt exists or not
$fo = fopen($file, "w"); //If data.txt file dosen't exists then to create a new
fwrite($fo, "0"); // Start to count from zero
fclose($fo); // closing file
}
@$click = $_POST["count"]; //Getting button value with POST method
if(isset($click)){ // Checking is set of not, it's a technique to get click
di(); //calling our function di()
}
function di(){
global $file; //making our file varail which contains file name global
$clicks = file($file); //reading our data.txt file
$clicks["0"]++; // incrementing 1, for example if value is 1 then to add 1
$fo = fopen($file, "w"); //opening our file
fwrite($fo, $clicks["0"]);//writing our incremented value
fclose($fo); // closing file
echo $clicks["0"]; // printing total numbers of clicks
}
?>
<form method="POST" action="counter.php">
<input type="submit" value="Download Now" name="count" />
</form>

Make it look more beautiful by adding few CSS and add it on your site :).

1 comment:

Your Comment Will Be Visible After Approval, Thanks !