How to generate one time download link using PHP

Last updated on February 25th, 2022 at 06:13 pm

Get IP Address And Generate Time Limited Download Link Using PHP

File sharing websites use different logic to expire the download link[They use methods like temporary file location, Databases, Javascript etc.,], You might be wondering how they do that?

In this tutorial I am going to show you a simple script that performs MD5 encryption using the details like IP address, Current Date, IP Address and Path. Let us call it Download.php. This script will create a unique data that will be transferred to another php script using GET method and then performs the download.

In the Download.php script you can also set time limit for the file to be active for that unique URL. Once that time limit is completed the user will get a expiry notification. Our current script has 2 minutes[120 seconds] validity. You can change this according to your need.

Once the user clicks the hyperlink that has the MD5 encrypted value, It gets redirected to a php script [File.php] that will do the comparison of value passed and then initiate the file download. You are free to modify this script according to your logic. My agenda is to provide you a basic idea on how this file download and expire link logic can be implemented on your website.

The download.php file has the below contents

$salt = 'Lock it now';
$path = '/file.php';
$timestamp = time() + 120; // 2 Min Validity
$date = date("H");
$hash = md5($salt . $ip . $date . $path); // order isn't important at all... just do the same when verifying
$url = "{$path}?s={$hash}&t={$timestamp}"; // use this as DL url
echo "<h2><a href='".$url."'>Download</a>";

Now the file.php script can be created by copying the below details

$salt = 'Lock it now';
$path = '/file.php';
$hashGiven = $_GET['s'];
$timestamp = $_GET['t'];
$date = date("H");
$hash = md5($salt . $ip . $date . $path);
if($hashGiven == $hash && $timestamp >= time()) {
echo "<h2>Link is active, Refresh this webpage after 2 minutes to see the link expired notification.";
    // serve file
} else {
    die('<h2>Link expired or invalid');

This is really a basic script and can be made powerful accordingly.


Click to rate this tutorial!
[Total: 4 Average: 5]

Leave a Reply

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