如何在单击链接时运行PHP计数器脚本?

时间:2012-11-15 20:29:14

标签: php

我有一个脚本在我的网站上访问页面时运行,它会更新一个值并将其存储在一个文本文件中,但我希望在我的网站上点击一个链接时运行相同的脚本,这个链接只是在我的web目录中打开一个文件,而不是实际的页面。这是脚本:

<?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);

?>

因此,如果我想在点击链接时运行此功能,是否有人知道我会在哪里执行此操作?以下是我的链接示例:

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

所以这个链接在一个新选项卡中打开文件,我正在试图弄清楚如何从链接点击中运行此文件,任何建议将不胜感激。

我正在考虑调用一个在单击链接时运行代码的PHP函数,但我无法做到。

非常感谢!

2 个答案:

答案 0 :(得分:8)

将您的计数脚本更新为:

<?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']");
?>

并使用链接:

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

答案 1 :(得分:1)

更新您的代码

另存为名称count.php

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

链接到网络

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