Help with Simple PHP Button / Link click counter

I am trying to add a simple ‘I Like This’ text button to pieces of my work. When the user clicks the ‘I like this’ button, I want a number to be recorded right next to the button, showing the total number of ‘likes’ so far. This is the first time I am using PHP to do anything, so I am completely lost - I can’t get any click counter to work that is simple enough for what I want to do and that will work without a MySQL database.

So far I have managed to set up a Javascript counter and it works great, but obviously it doesn’t remember the clicks once the user reloads the page - I need a permanent click counter. If this can be achieved using Javascript only, that would be ideal - but I don’t think there’s a way. Here is the code I have so far, and I just can’t get this to work:

CODE IN MY HTML PAGE (index.html):

I like it! <?php include("counter.php"); ?>

-----------------------------------------------

CODE IN MY PHP FILE (counter.php)

<?php
$filename = “counter.txt”;
$count= file($filename);
$count[0]++;
$file = fopen ($filename, “w”) or die (“Cannot find $filename”);
fputs($file, “$count[0]”);
fclose($file);
echo $count[0];
?>

TEXT FILE SAVED IN THE SAME DIRECTORY (counter.txt)

0


I think I might be calling the php file incorrectly in the my html page?
Can anyone help me? I am going to kill myself. Thanks

counter.php

<?php $file='/counter.txt'; $count=file_get_contents($file)+1; file_put_contents($file,$count,LOCK_EX); ?> <? echo $count; ?>

Remember javascript is client side (your browser) code whereas php is server side code. So after clicking a button by javascript, you must have to reload the whole page in case of any increment you want to store permanently in a file. If you want that incremented counter will be kept along with increment text on your page, but page will not be reloaded, then you need a ajax function.

counter.php

<?php $file='/counter.txt'; $count=file_get_contents($file)+1; file_put_contents($file,$count,LOCK_EX); ?> <? echo $count; ?>

Remember javascript is client side (your browser) code whereas php is server side code. So after clicking a button by javascript, you must have to reload the whole page in case of any increment you want to store permanently in a file. If you want that incremented counter will be kept along with increment text on your page, but page will not be reloaded, then you need a ajax function.

Sorry, double posts were created automatically. I didnot mention one thing. The code I have given does not need another script included. You can put it directly on index.html. So the page name will be index.php not counter.php. And before running it, creat the file ‘counter.txt’ with a digit ‘0’ (zero) as text. Otherwise it will show error without if(file_exists) statement.

Sponsor our Newsletter | Privacy Policy | Terms of Service