【问题标题】:PHP - Number of times downloadedPHP - 下载次数
【发布时间】:2009-10-27 11:05:32
【问题描述】:

如何显示一个计数器来计算文件下载的次数?我以前见过。 “下载了 450 次”。谢谢。

【问题讨论】:

  • 请让我们知道您到目前为止所做的尝试。

标签: php download counter


【解决方案1】:

不要让用户直接下载文件,而是通过如下脚本...

$file = $_REQUEST['file'];
$dldir = "downloads/";

if (
  (file_exists($dldir.$file) &&      // file exists
  (strpos($file, "../") === false))  // prevent an attacker from switching to a parent directory
) {

   header('Content-type: '.mime_content_type($dldir.file));
   header("Content-Transfer-Encoding: binary");
   header("Content-Length: " . filesize($dldir.$file) ."; "); 
   header('Content-Disposition: attachment; filename="'.$file.'"');

   echo file_get_contents($dldir.$file);

/** Update the counter here, e.g. by using mysql **/
} else {
   die("File not found");
}

【讨论】:

  • 在创建自定义下载脚本时,请注意不要允许下载 /etc/passwd 等文件。
  • 我会指定从哪个文件夹获取文件,不要让(就像 Kaivos.. 说的)用户像 /etc/passwd 一样劫持你的文件
【解决方案2】:

如果你想用 PHP 来做,你需要在 PHP 脚本中控制下载。基本上归结为以下两行伪代码:

set_number_of_downloads(get_number_of_downloads() + 1);
readfile($file_being_downloaded);

【讨论】:

    【解决方案3】:

    There你去。 另外,如果您更喜欢使用 MySQL 进行持久化,还有this 解决方案。

    【讨论】:

      【解决方案4】:

      在 Apache 上,您可以在请求文件时让 mod_rewrite 更新数据库。这样做的好处是发送速度快(可以使用sendfile),而且你不必改变你的URL或目录结构。

      #!/usr/bin/perl
      $| = 1;
      $dbh = DBI->connect("dbi:mysql:database=; host=localhost; user=; password=")
      or die "Connecting from PHP to MySQL database failed: $DBI::errstr";
      while (<STDIN>) {
          $dbh->query(... update database ...);
          print $_;
      }
      

      http://httpd.apache.org/docs/2.2/mod/mod_rewrite.html#rewriteengine

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-03-10
        • 2011-11-05
        • 1970-01-01
        • 2012-03-06
        • 2011-09-23
        • 1970-01-01
        相关资源
        最近更新 更多