Question

I am new to this and I am having problems trying to get my website to count the number of times a files has been downloaded. The website has download buttons linking to the files which are stored on my database, and I would like to be able to count the amount of downloads per file to display as a statistic, ideally once they click the link to download, the column in the files table should be incremented, but I cannot wrap my head around it. please help?

    <?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.';
   }
    ?>
Was it helpful?

Solution

The download link would point to a php file, such as download.php?id=123 -- this file would then take the ID and check the downloads database. If the ID exists, you run a query such as UPDATE files SET downloads = downloads + 1 WHERE id = 123.

Afterwards, you set the headers using header() to set content-type. Then use readfile().

See How to force file download with PHP on how to set headers and force a download.

Cheers!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top