Home arrow MySQL arrow Page 2 - Download Counting with Apache and PHP
MYSQL

Download Counting with Apache and PHP


Want to let your web site visitors download files while you can track the number of downloads at the same time? If so, Martin has the solution for you...

Author Info:
By: Martin Tsachev
Rating: 5 stars5 stars5 stars5 stars5 stars / 8
December 08, 2002
TABLE OF CONTENTS:
  1. · Download Counting with Apache and PHP
  2. · How Some of the Others Do It

print this article
SEARCH DEVARTICLES

Download Counting with Apache and PHP - How Some of the Others Do It
(Page 2 of 2 )

Some sites present you with a URL like http://www.example.com/download.php?file=/foo/bar, which is less than perfect. Being a Windows user (well sometimes), I expect that when I add a file to my download manager I'll see the filename in the list - unfortunately the result from adding a file from such a link is the meaningless download.php in your file list.

Some sites present you with a URL like http://www.example.com/download.php?file=/foo/bar, which is less than perfect. Being a Windows user (well sometimes), I expect that when I add a file to my download manager I'll see the filename in the list - unfortunately the result from adding a file from such a link is the meaningless download.php in your file list.

While the method mentioned above is easy to implement, it is not the best way to do it. We want visitors to see the real filename as the URL and not as a query string. So what we'll do internally is exactly the same as in the above example but this time the visitor will see the real filename.

How Do We Do It
Our URLs will be in the form of http://www.example.com/foo/bar, which makes more sense, doesn't it?

What Do We Need
  • Apache compiled with mod_rewrite (off by default, you need to add --enable-module=rewrite to your configure line)
  • PHP as the scripting engine with the Pear DB library available
  • A database such as MySQL, to store the downloadable data
Apache's Configuration

Options +FollowSymLinks
RewriteEngine On
RewriteBase /foobar/
RewriteRule download/send.php - [L]
RewriteRule download/(.+\..+)$ download/send.php?file=$1 [L]


You can put this block of code in a .htaccess file in the /foobar/ directory. Your downloads should be in /foobar/download/ - these are the directories accessible by the paths mentioned from your webserver.

What we do is switch on FollowSymLinks, which is required by mod_rewrite, if you don't need other options you can remove the +. We turn on the rewrite engine, which is off by default and then set the base location for the URI rewrites.

The next two lines are our rewrite rules. If the request is for send.php (our script that counts downloads) we don't modify it. If we get a request for download/foo.bar, then that will become download/send.php?file=foo.bar for Apache (the rewrite base is prepended). The rule processes only filenames with extensions.

The Download Counter

<?php

$file = isset($_GET['file']) ? trim($_GET['file']) : '';

if (!$file) {
die("Error");
}


if ( substr_count($file, '..') > 0 or substr($file, 0, 1) == '/' ) {
die("Invalid filename.");
}

$path = dirname($_SERVER['PATH_TRANSLATED']) . '/' . $file;

if ( !file_exists($path) ) {
die("File not found: $file");
}

$ext = explode('.', $file);
if ( sizeof($ext) < 2 ) {
die("Invalid filename: should have extension");
}


We do some checking first -- you should never display files to visitors that they have requested without checking for unwanted characters like ../ or / at the start of the filename.

The $path's value is set to the directory containing our script and the filename requested. We then check if the file really exists and if it has an extension:

$ext = $ext[sizeof($ext)-1];

switch ($ext) {
case 'tgz' :
$type = 'application/x-gzip';
break;

case 'php' :
$type = 'text/html';
break;

default :
$type = 'text/plain';
}

header("Content-type: $type");


By default PHP sends a content type header of text/html to the browser, so we need to modify it when this is not right. You should add more extension ->

MIME type pairs if you serve different file types. We've sent text/html for PHP files because we want to present them syntax highlighted - our script is something like a download counter and a PHP file browser.

Because we send a HTTP header, there should be nothing sent to the browser before the last line of the block above. Output buffering can be used as a way around this but it's not needed here.

$fd = fopen ($path, "r");
$code = fread ($fd, filesize($path));
fclose ($fd);

switch ($ext) {
case 'php' :
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/1999/REC-html401-19991224/loose.dtd">
<html>
<head>
<title><?php echo $file?> syntax highlighted</title>
</head>
<body>
<?php
highlight_string($code);
?>
</body>
</html>
<?php
break;

default :
echo $code;
}


This is the part that sends the file to the browser or presents the highlighted PHP file. The functions used are binary safe so you can send every type of file -- not only text.

require_once('../../config.php');
$db = db_connect();

$sql = "UPDATE download_file SET count=count+1 WHERE file = '$file' ";

$db->query($sql);
?>


The final function actually counts the download. As you can see from the code above, we include a file with our database info first. We connect to the database with our predefined function db_connect(), which returns a PEAR::DB instance.

The query updated the download_file table, which holds the download files and the number of times that they have been downloaded. We increase the count field by one for our file.

Note: Never make the mistake to first SELECT the count value, increment it in PHP and then write it to the database.
DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.

blog comments powered by Disqus
MYSQL ARTICLES

- MySQL and BLOBs
- Two Lessons in ASP and MySQL
- Lord Of The Strings Part 2
- Lord Of The Strings Part 1
- Importing Data into MySQL with Navicat
- Building a Sustainable Web Site
- Creating An Online Photo Album with PHP and ...
- Creating An Online Photo Album with PHP and ...
- PhpED 3.2 More Features Than You Can Poke ...
- Creating An Online Photo Album with PHP and ...
- Creating An Online Photo Album with PHP and ...
- Security and Sessions in PHP
- Setup Your Personal Reminder System Using PHP
- Create a IP-Country Database Using PERL and ...
- Developing a Dynamic Document Search in PHP ...

Watch our Tech Videos 
Dev Articles Forums 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
Contact Us 
Site Map 
Privacy Policy 
Support 

Developer Shed Affiliates

 




© 2003-2017 by Developer Shed. All rights reserved. DS Cluster - Follow our Sitemap
Popular Web Development Topics
All Web Development Tutorials