Skip to content

Download script using PHP

This is a short PHP script that I use on my site to handle downloads. Sure it’s easy to just link to the zip, but this allows me to keep track of how many times each file has been downloaded which I then use to rank the fonts on popularity.

< ?php

if (!is_numeric($_GET&#91;'id'&#93;))

$rs = mysql_query("SELECT file_name FROM table WHERE id='".$_GET&#91;'id'&#93;."' LIMIT 1");
if (mysql_num_rows($rs)==0)
header("HTTP/1.0 404 Not Found");
$row = mysql_fetch_row($rs);
$fhandle = fopen('files/'.$row&#91;0&#93;, 'rb');

$zip_data = fread($fhandle, filesize('files/'.$row&#91;0&#93;));

header("Content-type: application/zip");
header('Content-Disposition: attachment; filename="'.$row&#91;0&#93;.'"');
echo $zip_data;

//    Update download counter
mysql_query("UPDATE table SET download_counter=download_counter+1 WHERE id='".$_GET&#91;'id'&#93;."' LIMIT 1");


The actual script uses a slug for each font similar to how WordPress uses the permalink structure. I decided to go this way rather than an id number because it would be neater. Plus the download link is /font_slug/download/ rewritten with a mod_rewrite call to this script.

I’ve seen lots of download management scripts that are called using something similar to download.php? This is potentially a really big security risk. If somebody typed in download.php?filename=/home/yourusername/.htpasswd they might be able to get your username and password. For that matter download.php?filename=/etc/httpd/conf/httpd.conf would pull up your Apache config file if your server isn’t configured tightly enough.

Along the same security lines, lines 4-7 of the code above make sure that the id number passed is numeric to keep people from trying to send random commands to your database server.

Published inProgramming

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *