如何在PHP中强制下载和计数下载

时间:2019-02-15 16:32:25

标签: php

我的服务器上有一个文件(.zip,.msi等),我们会尽力保护它。我知道会话以及引荐来源都可能被欺骗。我们要么要求您来自我们的下载页面(开始会话),要么来自某个特定的合作伙伴。我有所有的工作。我想插入Google Analytics(分析),但我读过插入js / html会破坏下载。我只想创建然后写入txt文件,并捕获每次下载的日期并创建总下载的运行计数。这是我强制执行下载的代码-该文件位于直接调用的文件中,不会使用户离开合作伙伴网站:

<?php
    session_start();
    $ref = $_SERVER['HTTP_REFERER'];
    $refData = parse_url($ref);
    if(time() - $_SESSION['time'] < 2000 || ($refData['host'] == 'partnersite.com'))  {
        $path = '/var/www/vhosts/example.org/dir/dir/dir/App.Install.de-de.msi';
        $mm_type="Content-type: application/x-ole-storage";
        header("Pragma: public");
        header("Expires: 0");
        header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
        header("Cache-Control: public");
        header("Content-Description: File Transfer");
        header("Content-Type: " . $mm_type);
        header("Content-Length: " .(string)(filesize($path)) );
        header('Content-Disposition: attachment; filename="'.basename($path).'"');
        header("Content-Transfer-Encoding: binary\n");
        readfile($path);

        //try and write to file and count downloads
        $current_count = file_get_contents('count');
        $f = fopen('count', 'w+');
        fwrite($f, $current_count + 1);
        fclose($f);

        exit();
    } else { ?>
        <?php header("Location: https://example.org/404.php");
        die(); ?>
    <?php }
?>

同样,它的工作原理与我希望它强制并“软”保护下载免于热链接一样。我需要在某处创建“ count.php”,而不要重写,然后关闭它。

3 个答案:

答案 0 :(得分:1)

一旦您致电readfile(),您就将交出控制权。

在调用之前进行记录,它将起作用。

您可以保留一个计数器或写入一个日志文件。由于您已经知道如何写入文件,因此详细信息由您决定。

答案 1 :(得分:0)

您不必跟踪count,因为您可以简单地计算文件的行数以查看下载量。 https://stackoverflow.com/a/2162528/296555

if(time() - $_SESSION['time'] < 2000 || ($refData['host'] == 'partnersite.com'))  { 
    // Sudo code - see real example here - https://stackoverflow.com/a/19898993/296555
    // Write to log file before initiating the download.
    $log = current date time
    file_put_contents('./log_file.log', $log, FILE_APPEND);

    // Now, do the download part
    ...

答案 2 :(得分:0)

(代表问题作者发布)

写到日志很容易,并且可以通过答案中提供的链接来完成。我最终需要一个更强大的解决方案,并且该解决方案可以与我们现有的Google Analytics(分析)设置一起使用。因此,我使用了Google的Measurement Protocol及其Hit Builder进行测试。这是SO上的good source of info