Downloads Counter

2

Could anyone help me do the following:

I have a download site where I want to do a download counter for each page and that when clicked, the number of downloads on the page will be updated automatically.

    
asked by anonymous 17.07.2015 / 07:58

3 answers

6

Hello, here is an exact tutorial related to what you are looking for.

Here you check the example demo by running and doing exactly what you need.

Step 1 of 7 - Create Database

CREATE TABLE 'download_manager' (
  'id' int(6) unsigned NOT NULL auto_increment,
  'filename' varchar(128) collate utf8_unicode_ci NOT NULL default '',
  'downloads' int(10) unsigned NOT NULL default '1',
  PRIMARY KEY  ('id'),
  UNIQUE KEY 'filename' ('filename')
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

Step 2 of 7 - configuration.php

<?php
 $db_host       = '';
 $db_user       = '';
 $db_pass       = '';
 $db_database   = ''; 
 $directory='files';
?>

Step 3 of 7 - connect.php

<?php
  require_once 'configuration.php';
  $link = @mysql_connect($db_host,$db_user,$db_pass) or die('Unable to       establish a DB connection');
  mysql_set_charset('utf8');
  mysql_select_db($db_database,$link);
?>

Step 4 of 7 - demo.php

<?php
// Error reporting:
error_reporting(E_ALL^E_NOTICE);

// Including the DB connection file:
require 'connect.php';

$extension='';
$files_array = array();


/* Opening the thumbnail directory and looping through all the thumbs: */

$dir_handle = @opendir($directory) or die("There is an error with your file directory!");

while ($file = readdir($dir_handle)) 
{
    /* Skipping the system files: */
    if($file{0}=='.') continue;

    /* end() returns the last element of the array generated by the explode() function: */
    $parts = explode('.',$file);
    $extension = strtolower(end($parts));

    /* Skipping the php files: */
    if($extension == 'php') continue;

    $files_array[]=$file;
}

/* Sorting the files alphabetically */
sort($files_array,SORT_STRING);

$file_downloads=array();

$result = mysql_query("SELECT * FROM download_manager");

if(mysql_num_rows($result))
while($row=mysql_fetch_assoc($result))
{
    /*  The key of the $file_downloads array will be the name of the file,
        and will contain the number of downloads: */

    $file_downloads[$row['filename']]=$row['downloads'];
}

?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>PHP &amp; MySQL File Download Counter | Tutorialzine demo</title>

<link rel="stylesheet" type="text/css" href="styles.css" />
<link rel="stylesheet" type="text/css" href="fancybox/jquery.fancybox-1.2.6.css" media="screen" />

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script><scripttype="text/javascript" src="script.js"></script>

</head>

<body>

<h1>PHP &amp; MySQL File<br />Download Counter</h1>
<h2>Go back <a href="http://tutorialzine.com/2010/02/php-mysql-download-counter/">to the tutorial &raquo;</a></h2>


<div id="file-manager">

    <ul class="manager">
    <?php 

        foreach($files_array as $key=>$val)
        {
            echo '<li><a href="download.php?file='.urlencode($val).'">'.$val.' 
                    <span class="download-count" title="Times Downloaded">'.(int)$file_downloads[$val].'</span> <span class="download-label">download</span></a>
                    </li>';
        }

    ?>
  </ul>

</div>


<p class="tutInfo">This is a tutorialzine demo. View the <a href="http://tutorialzine.com/2010/02/php-mysql-download-counter/">original tutorial</a>, or download the <a href="demo.zip">source files</a>.</p>

<!-- BSA AdPacks code. Please ignore and remove. -->
<script type="text/javascript" src="http://cdn.tutorialzine.com/misc/adPacks/v1.js"async></script></body></html>

Step5of7-download.php

<?php//Errorreporting:error_reporting(E_ALL^E_NOTICE);//Includingtheconnectionfile:require('connect.php');if(!$_GET['file'])error('Missingparameter!');if($_GET['file']{0}=='.')error('Wrongfile!');if(file_exists($directory.'/'.$_GET['file'])){/*Ifthevisitorisnotasearchengine,countthedownoad:*/if(!is_bot())mysql_query("   INSERT INTO download_manager SET filename='".mysql_real_escape_string($_GET['file'])."'
                    ON DUPLICATE KEY UPDATE downloads=downloads+1");

    header("Location: ".$directory."/".$_GET['file']);
    exit;
}
else error("This file does not exist!");


/* Helper functions: */

function error($str)
{
    die($str);
}


function is_bot()
{
    /* This function will check whether the visitor is a search engine robot */

    $botlist = array("Teoma", "alexa", "froogle", "Gigabot", "inktomi",
    "looksmart", "URL_Spider_SQL", "Firefly", "NationalDirectory",
    "Ask Jeeves", "TECNOSEEK", "InfoSeek", "WebFindBot", "girafabot",
    "crawler", "www.galaxy.com", "Googlebot", "Scooter", "Slurp",
    "msnbot", "appie", "FAST", "WebBug", "Spade", "ZyBorg", "rabaz",
    "Baiduspider", "Feedfetcher-Google", "TechnoratiSnoop", "Rankivabot",
    "Mediapartners-Google", "Sogou web spider", "WebAlta Crawler","TweetmemeBot",
    "Butterfly","Twitturls","Me.dium","Twiceler");

    foreach($botlist as $bot)
    {
        if(strpos($_SERVER['HTTP_USER_AGENT'],$bot)!==false)
        return true;    // Is a bot
    }

    return false;   // Not a bot
}
?>

Step 6 of 7 - script.js

** $ (document) .ready (function () {     / * This code is executed after the DOM has been completely loaded * /     $ ('ul.manager a'). click (function () {

    var countSpan = $('.download-count',this);
    countSpan.text( parseInt(countSpan.text())+1);
});

}); **

Step 7 of 7 - style.css

body,h1,h2,h3,p,quote,small,form,input,ul,li,ol,label{
    /* Simple page reset */
    margin:0;
    padding:0;
}

body{
    /* Setting default text color, background and a font stack */
    color:#555;
    font-size:0.825em;
    background: #fcfcfc;
    font-family:Arial, Helvetica, sans-serif;
}

#file-manager{
    background-color:#EEE;
    border:1px solid #DDD;
    margin:50px auto;
    padding:10px;
    width:400px;
}

ul.manager li{
    background:url("img/bg_gradient.gif") repeat-x center bottom #F5F5F5;
    border:1px solid #DDD;
    border-top-color:#FFF;

    list-style:none;
    position:relative;
}

ul.manager li a{
    display:block;
    padding:8px;
}

ul.manager li a:hover .download-label{
    /* When a list is hovered over, show the download green text inside it: */
    display:block;
}

span.download-label{
    background-color:#64B126;
    border:1px solid #4E9416;
    color:white;
    display:none;
    font-size:10px;
    padding:2px 4px;
    position:absolute;
    right:8px;
    text-decoration:none;
    text-shadow:0 0 1px #315D0D;
    top:6px;

    /* CSS3 Rounded Corners */

    -moz-border-radius:3px;
    -webkit-border-radius:3px;
    border-radius:3px;
}

span.download-count{
    color:#999;
    font-size:10px;
    padding:3px 5px;
    position:absolute;
    text-decoration:none;
}

/* The styles below are only necessary for the demo page */

h1{
    background:#f0f0f0;
    border-bottom:1px solid #eaeaea;
    font-size:1.5em;
    font-weight:normal;
    margin-bottom:15px;
    padding:15px;
    text-align:center;
}

h2 {
    font-size:0.9em;
    font-weight:normal;
    padding-right:40px;
    position:relative;
    right:0;
    text-align:right;
    text-transform:uppercase;
    top:-48px;
}

a, a:visited {
    color:#0196e3;
    text-decoration:none;
    outline:none;
}

a:hover{
    text-decoration:underline;
}

p.tutInfo{
    /* The tutorial info on the bottom of the page */
    padding:10px 0;
    text-align:center;
    position:fixed;
    bottom:0px;
    background:#f0f0f0;
    border-top:1px solid #eaeaea;
    width:100%;
    z-index:15;
}

h1,h2,p.tutInfo{
    font-family:"Myriad Pro",Arial,Helvetica,sans-serif;
}
    
17.07.2015 / 13:33
1

You can do this with PHP and MySQL:

$sql = "Select CAMPO from TABELA where PAGINA like 'NOME DA PÁGINA'";
$numero= mysql_query($sql);

while ($tipo = mysqli_fetch_array($numero)) {
    echo: "Nº. de Downloads: "  . $tipo['CAMPO'];
}
    
17.07.2015 / 09:18
1

An interesting solution is to use .txt files to store this record since it is not so much a thing to have in the database.

Example:

Create a file named download.php with the following content:

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

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

      <?php
      $filePath = $Down.".txt";

      /*Se o arquivo existe, leia o contador que ele possui senão inicialize com 0*/
$count = file_exists($filePath) ? file_get_contents($filePath) : 0;

// Incrementa o novo valor e subscreve com o novo número
file_put_contents($filePath, ++$count);

// Mostra o contador atual
echo "Downloads:".$count; ?>

< /body>
</html >

PHP - Count downloads

    
17.07.2015 / 13:19