deucalion0 deucalion0 - 4 months ago 27
PHP Question

How can I run a PHP counter script when clicking a link?

I have a script that runs when a page is visited on my site, it updates a value and stores it in a text file, but I want to run the same script when a link is clicked on my site, this link just opens a file in my web directory, not an actual page. here is teh script:

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

?>


So if I want to run this when my link is clicked does anyone know where I would do this? Here is an example of my link:

<li><a href="files/file.pdf" target="blank" title="File">File</a></li>


So this link opens the file in a new tab, I am busting my brains trying to figure out how to run this from the link click, any advice would be appreciated.

I was thinking about calling a PHP function which ran the code when the link was clicked, but I couldn't do it.

Many thanks!

Answer

Update your count script to:

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

header("Location: ".$_GET['file']");
?>

And use link:

<a href="count.php?file=files/file.pdf" target="blank" title="File">File</a>
Comments