【问题标题】:PHP - Count downloadsPHP - 计数下载
【发布时间】:2011-11-05 01:11:42
【问题描述】:

我想用 PHP 计算文件下载次数。下载编号应存储在 .TXT 文件中。

如何做到这一点? 谢谢 乌力

【问题讨论】:

  • 您只需要一个文件还是多个文件?
  • 是的,只针对一个文件。 (这是一个 .zip 文件)
  • 相关:stackoverflow.com/questions/146/… - 我特别喜欢 grep'ing access.log
  • 我已经编辑了代码以包含一个初始变量初始化,该初始化变量之前被代码格式化程序呈现为不可见。此外,我将 $count++ 更改为 ++$count,以便在写入之前增加 并且还处理尚无文件存在时的初始情况。

标签: php


【解决方案1】:
$current_count = file_get_contents('count');
$f = fopen('count', 'w+');
fwrite($f, $current_count + 1);
fclose($f);

header("Location: file.zip");

【讨论】:

  • 如果文件下载中断了怎么办?它还会计算广告下载量吗?
  • @daslicht 是的,它会算作一次下载。代码所做的是 1) 增加一个计数器 2) 将用户重定向到要下载的文件。如果用户在提示后选择不按“保存”或“下载”,仍将按下载一样计算。
【解决方案2】:

创建一个名为download.php 的文件,其内容如下:

<?php
 $Down=$_GET['Down'];
?>

<html>
 <head>
  <meta http-equiv="refresh" content="0;url=<?php echo $Down; ?>">
 </head>
 <body>

 <?php

  $filePath = $Down.".txt";

  // If file exists, read current count from it, otherwise, initialize it to 0
  $count = file_exists($filePath) ? file_get_contents($filePath) : 0;

  // Increment the count and overwrite the file, writing the new value
  file_put_contents($filePath, ++$count);

  // Display current download count
  echo "Downloads:" . $count;
 ?> 

 </body>
</html>

在另一个页面中放一个指向它的链接,并将要下载的文件作为参数:

download.php?Down=download.zip

答案参考Dreamincode answer to a similar question

【讨论】:

  • 这看起来不错,但计数器不工作。我错过了什么? .txt 文件以“0”计数和 CHMOD 777 开头。
  • @Uli 创建download.php文件后究竟应该做什么?
  • 小心,如果您的网站在互联网上!任何人都可以使用此解决方案从您的服务器下载所有内容。
  • @knobli 这不是真的 - 这个实现只在文件和实际文件的链接之间进行重定向,AFAIK 没有引入新的安全风险。
  • 如果文件下载中断了怎么办?它还会计算广告下载量吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-03
相关资源
最近更新 更多