Home arrow PHP arrow Page 2 - Simple and Secure PHP Download Script with Limits Tutorial

The PHP Download Script (download.php) - PHP

You might need to offer some of your website's content for downloading. For example, many sites commonly offer downloads of PDF and MP3 files. If you do this, you'll want to set up your download system so that it can give you certain information and perform certain tasks, like telling you how often certain files have been downloaded or limiting the number of downloads. This article will show you how to create a download script that accomplishes this and more.

  1. Simple and Secure PHP Download Script with Limits Tutorial
  2. The PHP Download Script (download.php)
By: Codex-M
Rating: starstarstarstarstar / 13
December 22, 2010

print this article



Below is the complete PHP download script (download.php):


//Start PHP session because you need to compare the session received if it is using correct key.


//Get referer

$referer = $_SERVER['HTTP_REFERER'];

//Define the correct session value, the value of $pass should be the same with $key as discussed in the previous section no.8.

$keymatch= $_SESSION['key'];
$pass='This is your example key, please change this.';
$md5value= md5($pass);

//Validate user by checking if the user has correct session set and referring page

if (($referer=="http://www.yourdomain.com/thisisyourdownloadpage.php")&& ($keymatch==$md5value)) {

//User is valid, connect to MySQL database

$username = "Your MySQL database username";
$password = "Your MySQL database password";
$hostname = "Your MySQL database hostname";
$database = "Your MySQL database name";
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
$selected = mysql_select_db($database,$dbhandle)
or die("Could not select $database");

//Get the IP address of the user

$ipdownloader= $_SERVER['REMOTE_ADDR'];

//Sanitize input

$ipdownloader = mysql_real_escape_string($ipdownloader);

//check if the user already downloaded before

if (!($fetch = mysql_fetch_array( mysql_query("SELECT `ipaddress` FROM `downloads` WHERE `ipaddress`='$ipdownloader'")))) {

//No records found, fresh downloader
//Prepare content for downloading

//Define the content type and show force download attachment dialog

header('Content-Disposition: attachment; filename="http://www.yourdomain.com/ebookfordownloads/ebook.pdf"');

//Stream the PDF file for downloading using PHP readfile function
//The readfile is using absolute server path
//You can determine this path by uploading a php script to the folder containing the download material.


//Record downloader IP address to MySQL database and set download to 1

mysql_query("INSERT INTO `downloads` (`ipaddress`,`downloadtimes`) VALUES('$ipdownloader','$firstdownload')")
or die(mysql_error());
else {

//Already has downloading records; check how many times the user downloaded the ebook

$result = mysql_query("SELECT `downloadtimes` FROM `downloads` WHERE `ipaddress`='$ipdownloader'")
or die(mysql_error());
$row = mysql_fetch_array($result)
or die("Invalid query: " . mysql_error());
$downloadtimes = $row['downloadtimes'];
if ($downloadtimes < 3) {

//the user downloaded less than 3 times, the user still eligible to download the ebook. Stream the PDF to the user for force downloading.

header('Content-Disposition: attachment; filename="http://www.yourdomain.com/ebookfordownloads/ebook.pdf"');

//Update download records of the user by incrementing it with 1

$updateddownloadtime = $downloadtimes + 1;

//Update download times information of the user in MySQL database

mysql_query("UPDATE `downloads` SET `downloadtimes` = '$updateddownloadtime' WHERE `ipaddress` = '$ipdownloader'")
or die(mysql_error());
else {

//The user already exceeds the downloading limit, prevent downloading
//destroy session for the user


//Redirect the user back to the previous page using meta refresh.

echo "<meta http-equiv='refresh' content='0;url=http://www.yourdomain.com/thisisyourdownloadpage.php'>";

//Close the MySQL database connections

else {

//Invalid user -fails during user authentication, either bad wrong session key or referring page.

//Destroy any session.


//Redirect the user back to the download page.

echo "<meta http-equiv='refresh' content='0;url=http://www.yourdomain.com/thisisyourdownloadpage.php'>";

Implementation Tips

Below are the recommended tips for implementation:

  1. You can download the complete PHP script here: http://bit.ly/eCnDvZ 
  2. Define an upload folder where your content is placed, and add a download link to your download page (details in the previous section); also, upload the required htaccess.
  3. Put your own database connection parameters and download path in the download.php script.
  4. Upload the download.php script to the root directory of your website.
  5. You can view the number of unique downloads in the MySQL database, or write a customized script (accessible only by administrators) to retrieve the number of downloads.

>>> More PHP Articles          >>> More By Codex-M

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort


- Hackers Compromise PHP Sites to Launch Attac...
- Red Hat, Zend Form OpenShift PaaS Alliance
- PHP IDE News
- BCD, Zend Extend PHP Partnership
- PHP FAQ Highlight
- PHP Creator Didn't Set Out to Create a Langu...
- PHP Trends Revealed in Zend Study
- PHP: Best Methods for Running Scheduled Jobs
- PHP Array Functions: array_change_key_case
- PHP array_combine Function
- PHP array_chunk Function
- PHP Closures as View Helpers: Lazy-Loading F...
- Using PHP Closures as View Helpers
- PHP File and Operating System Program Execut...
- PHP: Effects of Wrapping Code in Class Const...

Developer Shed Affiliates


Dev Shed Tutorial Topics: