Download Counter

Asked

Viewed 1,636 times

2

I wonder if someone could help me do the following:

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

  • What have you done? You can show the code you have?

3 answers

6


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

Here you check the demo of the example 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>
<script type="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>

Step 5 of 7 - download.php

<?php

// Error reporting:
error_reporting(E_ALL^E_NOTICE);

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

if(!$_GET['file']) error('Missing parameter!');
if($_GET['file']{0}=='.') error('Wrong file!');

if(file_exists($directory.'/'.$_GET['file']))
{
    /* If the visitor is not a search engine, count the downoad: */
    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;
}
  • 2

    Eduardo, although the links can answer the question, it is good to add the content to the body of the answer, so that it can be understood without having to follow the links and so they are only reference. This is also important because if the links break the answer is invalid.

  • 1

    Absolutely, I’ll fix it. Thank you.

  • While this link may answer the question, it is best to include the essential parts of the answer here and provide the link for reference. Replies per link only can be invalidated if the page with the link is changed.

  • Ready, step by step @Kaduamaral

  • Ready @Ricardo, I explained step by step.

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'];
}
  • But this does not update the number of downloads, it is necessary to make a update of the number after the select.

1

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

Example:

Create a file called 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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.