track download link

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Anant
Forum Commoner
Posts: 66
Joined: Wed Jul 14, 2010 11:46 am

track download link

Post by Anant »

Hi,

i am providing a pdf file download option in my site. But i need to track the number of downloads and stop the download after it reach the limit.

I know google analytics can tell the number of clicks but i am looking for another way may be increasing counter with every time the link is clicked.

i was trying this -

Code: Select all

 <a abc.php?id=<?php echo r['id'] ?> onclick="++count" > test </a>
and then updating the database with new count value but this certainly isn't helping. count value is same.

Is thr anything am doing wrong in above line or please let me know if there is better way to do this ?

Thanks
phppro62
Forum Newbie
Posts: 16
Joined: Wed Oct 27, 2010 2:45 am

Re: track download link

Post by phppro62 »

Hi mate
It's really along stoy if you want to follow it follow step by step:

let's start

Each file will have a corresponding row in the database, where the total number of downloads is saved. PHP will update the MySQL database and redirect the visitors to the appropriate files.

To track the number of downloads, you just need to upload your files to the files folder, and use a special URL to access them.

STEP 1 XHTML demo.php

Code: Select all

<?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: */
	$extension = strtolower(end(explode('.',$file)));
	
	/* 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 & MySQL File Download Counter </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 & MySQL File Download Counter</h1>


    
<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">PHPPR62 </p>


</body>
</html>

STEP 2 CSS style.css

Code: Select all

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;
}







STEP 4 DBASE configuration.php

Code: Select all

<?php

/* Database config */

$db_host		= '';
$db_user		= '';
$db_pass		= '';
$db_database	= ''; 

/* End config */

/* File directory: */

$directory='files';

?>


STEP 6 MYSQL table.sql
create a dbase and put the codde below into SQL

Code: Select all

-
-- Table structure for table `download_manager`
--

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 7 CONNECT connect.php

Code: Select all

<?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 8 DOWNLOD download.php

Code: Select all

<?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 9 JSCRIPT script.js

Code: Select all

$(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);
	});
});

The last step create HTACCESS file in the directory where you'll put your download files
NOTE1: YOU SHOULD NAME YOUR DIRECTORY "files" BUT IF YOU WANT TO CHANGE THE NAME EDIT configuration.php
NOTE2: if you want to get some files appear to be download you should put some files in the files directory

Code: Select all


<Files *.*>
ForceType application/octet-stream
</Files>
Anant
Forum Commoner
Posts: 66
Joined: Wed Jul 14, 2010 11:46 am

Re: track download link

Post by Anant »

oh it's a very long story. can this be achieved in just increasing counter in onclick event of the a tag ?
phppro62
Forum Newbie
Posts: 16
Joined: Wed Oct 27, 2010 2:45 am

Re: track download link

Post by phppro62 »

Hi Anant
It can be acheived by one click . This is a secure script which i gave you .
The other way you can use the power of MYSQL function

you just creat a dbase then a table put two fields in it like ID and counter
then use
mysql_query("INSERT INTO table (ID,counter) VALUES (1,1)
ON DUPLICATE KEY UPDATE counter=counter+1");

this will update your table with any click that accure on your link and put +1 on the current value.
IF you need more help please tell me.
Anant
Forum Commoner
Posts: 66
Joined: Wed Jul 14, 2010 11:46 am

Re: track download link

Post by Anant »

mysql_query("INSERT INTO table (ID,counter) VALUES (1,1)
ON DUPLICATE KEY UPDATE counter=counter+1");
Hi,

Thanks for your input.

this worked well. But is there any way we can track if the user saved or open the pdf file in thr system..I guess not but just in case there is any way.
I know i can have google analytics but would prefer other way.

thanks
Post Reply