如何计算下载数据库中FILE的次数?

时间:2014-03-18 19:27:56

标签: php html sql download counter

我是新手,我在尝试让我的网站计算文件下载次数时遇到问题。该网站有下载按钮链接到存储在我的数据库中的文件,我希望能够计算每个文件的下载量,以显示为统计数据,理想情况下,一旦他们点击链接下载,列中的文件表应该递增,但我无法绕过它。请帮忙吗?

    <?php 
error_reporting(E_ALL ^ E_NOTICE); 
session_start(); 
$userid = $_SESSION['userid']; 
$username= $_SESSION['username']; 
?>

<?php

// Make sure an ID was passed
if(isset($_GET['id'])) {
// Get the ID
$id = ($_GET['id']);

// Make sure the ID is in fact a valid ID
if($id <= 0) {
    die('The ID is invalid!');
}
else {
    // Connect to the database
    $dbLink = new mysqli('dragon.kent.ac.uk', 'repo', '3tpyril', 'repo');
    if(mysqli_connect_errno()) {
        die("MySQL connection failed: ". mysqli_connect_error());
    }

    // Fetch the file information
    $query = "
        SELECT `mime`, `name`, `size`, `data`
        FROM `files`
        WHERE `id` = {$id}";
    $result = $dbLink->query($query);

    if($result) {
        // Make sure the result is valid
        if($result->num_rows == 1) {
        // Get the row
            $row = mysqli_fetch_assoc($result);



            // Print headers
            header("Content-Type: ". $row['mime']);
            header("Content-Length: ". $row['size']);
            header("Content-Disposition: attachment; filename=". $row['name']);

            // Print data
            echo $row['data'];


        }
        else {
            echo 'Error! No files exists with that ID.';
        }


    }
    else {
        echo "Error! Query failed: <pre>{$dbLink->error}</pre>";
    }
    @mysqli_close($dbLink);


    }
    }
  else {
    echo 'Error! No ID was passed.';
   }
    ?>

1 个答案:

答案 0 :(得分:1)

下载链接将指向一个php文件,例如download.php?id=123 - 此文件将获取ID并检查下载数据库。如果ID存在,则运行UPDATE files SET downloads = downloads + 1 WHERE id = 123之类的查询。

然后,您使用header()设置标头以设置内容类型。然后使用readfile()

请参阅How to force file download with PHP,了解如何设置标头并强行下载。

干杯!