简体   繁体   中英

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!

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>

Update your code

Save as name count.php

<?php
file_put_contents('hitcounter.txt', ((int) file_get_contents('hitcounter.txt')) + 1);
header('Location: ' . $_GET['url']);
?>

Link to web

<a href="count.php?url=http://askedboss.com" target="blank">CLICK HERE</a>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM