dsh7623 2014-09-28 16:57
浏览 55
已采纳

单击链接时点击计数器PHP / JS

I have a little script here that counts clicks when link is clicked and stores it in .txt file, but it works fine when I have only "click=yes" under href. But I can't make it to track clicks when I have link to external site.

Here is my code:

<?php
if(!file_exists('counter.txt')){
file_put_contents('counter.txt', '0');
}
if($_GET['click'] == 'yes'){
file_put_contents('counter.txt', ((int) file_get_contents('counter.txt')) + 1);
header('Location: ' . $_SERVER['SCRIPT_NAME']);
die;
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>counter example</title>
</head>
<body>
<h1><?php echo file_get_contents('counter.txt'); ?></h1>
<a href="http://www.google.com?click=yes" target="new">clickMe</a>
</body>
</html>

My guess is it has to do something with header('Location: ' . $_SERVER['SCRIPT_NAME']); but I can't figure it out so I could really use some help.

And is it somehow possible to have multiple links save to the same file, and when I show it on website it's sorted from largest number to smallest? I have an idea how to do it with MySQL database but I can't use it at place where this will be implemented.

Thanks in advance! Cheers!

  • 写回答

2条回答 默认 最新

  • dongyun3805 2014-09-28 17:04
    关注

    Your server never sees the URI being accessed as the client leaves your page. To do something like this, it may be best to set up a redirect which works like this

    <a href="/goto.php?href=http://www.google.com" target="_blank">click me</a>
    

    (Make sure the external site's URL is URL encoded as you're passing it as a GET component of a URL to your own page)

    Then in goto.php you store your click and send a redirect header

    if(!file_exists('counter.txt')){
        file_put_contents('counter.txt', '0');
    }
    file_put_contents('counter.txt', ((int) file_get_contents('counter.txt')) + 1);
    header('Location: ' . $_GET['href']);
    

    Now you can track these clicks, you can add your domain-specific counters in goto.php instead of your text file

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 CST仿真别人的模型结果仿真结果S参数完全不对
  • ¥15 误删注册表文件致win10无法开启
  • ¥15 请问在阿里云服务器中怎么利用数据库制作网站
  • ¥60 ESP32怎么烧录自启动程序
  • ¥50 html2canvas超出滚动条不显示
  • ¥15 java业务性能问题求解(sql,业务设计相关)
  • ¥15 52810 尾椎c三个a 写蓝牙地址
  • ¥15 elmos524.33 eeprom的读写问题
  • ¥15 用ADS设计一款的射频功率放大器
  • ¥15 怎么求交点连线的理论解?