CREATE EXPIRE DOWNLOAD LINK IN PHP MYSQL | BEST TUTORIAL

The Download File

Here is the download.php file, this file is the one that actually keeps tracks of the expired links, times the files is downloaded and provides the download if they meet all conditions. It also contains comments if you were to add future users, keep track of purchases and more.

 

<?php include('header.php'); ?>
<div class="container">
<div class="jumbotron"><p class="text-xl-center">
<?php
// retrieve link
if (isset($_GET["link"]) && preg_match('/^[0-9A-F]{40}$/i', $_GET["link"])) {
$link = $_GET["link"];
}else{
echo "<h1>Valid link not provided.</h1>";
exit();
}
//starting verification with the $ct variable
$ct=0;
$currenttime= $_SERVER["REQUEST_TIME"];
$currentdate = date('M d, Y h:i:s A', $currenttime);
echo 'Current Date '.$currentdate.'<br/>';
// verify link get necessary information we will need to preocess request
$result = $db->query("SELECT * FROM links WHERE link='$link' ") ;
while ($row = $result->fetch_assoc()) {
$linkdb = $row['link'];
$filedownload = $row['file'];
$tstamp = $row['tstamp'];
$expire = $row['expire'];
$counting = $row['counting'];
$newcount=$counting-1;</pre>
//convert timestamp to readable date the show expiration date and time
$date = date('M d, Y h:i:s A', $expire);
echo 'To Expire on '.$date.'<br/>';

// Check to see if link has expired
if ($currenttime > $expire) {
echo "We are so sorry the link has expired.";
exit();
// delete link so it can't be used again
mysqli_query($db,"DELETE FROM links WHERE link='$link' ");
exit();
}

if ($linkdb==$link) {
echo 'You have '.$newcount.' more times to access this link.';
mysqli_query($db,"UPDATE links SET counting='$newcount' WHERE link='$linkdb' ");
$ct=1;
}
else {
echo "Valid link not provided or link has expired.";
exit();
}
}

// delete link so it can't be used again
mysqli_query($db,"DELETE FROM links WHERE link='$link' AND counting < '1' ");

//FILE DOWNLOAD
//path to file
if($ct==1){
$path = '';
$path = "files/$filedownload";
echo $path;

$mime_type=mime_content_type($path);

header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.$path.'"');
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($path)); //Absolute URL
ob_clean();
flush();
readfile($path); //Absolute URL
exit();
}else{
echo '<p>This file has already been dowloaded the maximum number of times.</p>';
}
?>
</p>
</div>
<?php
include_once('footer.php'); ?>

 

Header, Footer  and Config Files

Here is the header, footer and config.php  files to properly include scripts we need.

Only cool people share!

header.php

<?php
date_default_timezone_set('America/New_York');
include('config.php');
?>
<html>
<head>
<title>Create A Link That Expires</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" type="text/css" >
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.5.2/animate.min.css">
<link href="style.css" rel="stylesheet" type="text/css" >
</head>
<body>

 

footer.php

</body>
</html>
<?php
$db->close();
?>

config.php

<?php
$db = mysqli_connect("localhost","root","","test");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}else{
echo "";
}
?>

Protect Your Files Folder

An important note is that you want to protect your files folder so that people cannot sneakily find out where you store your downloads, then just come and download all your files for free. You do this by including a htaccess file in the folder. I include it with the download files above. Here is what it looks like.

Deny From All

Conclusion For Creating  Expired Download Links in PHP

I hope you could get some use from this tutorial. Please remember that you can build on it. There are many things that you can do with this script. Please give me some feedback and I will create more like this.

Alternative Tutorials To Expire Links In PHP

If I could not help, there are several other tutorials online for this process. I will link them here.

[SOLVED] Creating Temporary Download Links – PHP Coding Help – PHP Freaks

Generate download file link in PHP – Stack Overflow

PHP Master | Generating One-Time Use URLs (sitepoint.com)

One Time Temporary Download Link with Expiration in PHP – CodexWorld

CREATE EXPIRE DOWNLOAD LINK IN PHP MYSQL | BEST TUTORIAL was last modified: July 27th, 2022 by Maximus Mccullough
CREATE EXPIRE DOWNLOAD LINK IN PHP MYSQ

Pages:Previous 1 2 3

12 Comments

  • Boban says:

    Hi
    Very good ! ! !
    How to upload multiple file and create ZIP file ?

  • Jake Roberts says:

    Mine won’t go over 100 mb and I followed to a T

  • Dragos says:

    Hi!b How to delete a link from the database and how to display in webpage existing links in the database (mysql) ? Thx

    • HI Dragos. On page 2 for the download.php file you will see this
      // delete link so it can't be used again
      mysqli_query($db,"DELETE FROM links WHERE link='$link' AND counting < '1' ");

      This code is responsible for deleting the link in the database. For displaying the link you would query the database. Something like this.

      $result = $db->query("SELECT * FROM links") ;

      while ($row = $result->fetch_assoc()) {

      echo $row[‘link’];

      }

  • Dragos says:

    I can only delete from the server the whole table of links, not each individual. I did some tests and there are links with a higher validity. I would like to be able to see all the submitted links on the index.php page and be able to delete them individually if I need to. If I try to add your script to the index.php page, I get the error:
    ( ! ) Warning: Unknown: Invalid date.timezone value ‘UTC+02.00’, we selected the timezone ‘UTC’ for now. in Unknown on line 0
    ( ! ) Parse error: syntax error, unexpected end of file in D:\wamp64\www\website\downloadlink\index.php on line 91
    downloadlink is the folder with all download from your website

  • This looks very cool! It is not exactly what I am looking for so I need to dig through it. If you could save me some time with understanding what this code is doing or point me to similar code for what I am trying to accomplish, so much the better. I’m still pretty new to PHP and other things.

    It appears as if the code takes a file referred from your own directory, then provides encryption to it before storing in a local data table with expiration and count data? Then download.php pulls the link from the table and spits it out…

    What I am working on is an e-commerce site selling books in digital format in .epub, .mobi or .zip files containing the .mp3 audio chapters.

    Both for promotional giveaways and sales, I need to provide a download link, but I do not want that link to be permanent — just open long enough for the customer to get the file before closing that path.

    So what do I need to do? I don’t need to do any uploading and I can hard code the time/date/count for downloads somewhere and change them as needed? Then use the ‘links’ data table for loading in those temporary URLs?

    I will keep working on this, but if you have any advice, it would be appeciated.

    Thanks

  • Walter Jones says:

    Using MAC but on Chrome, but when I upload a photo .jpg or .png and I click on the generated link, it doesn’t download directly it opens a page that shows code. Any ideas?

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.