-1

I have a one-time link like in this:

<?php
    session_start();
    $file1 = "img/img1.jpeg";
    $key1 = md5($file1 . microtime());
    $_SESSION[$key1] = $file1;
    $link1 = "download.php?key=" . $key1;
    echo "<a href='" . $link1 . "'id='button1'>download</a><br>";

?>

download.php

<?php
session_start();
// Get the key from the query string
$key = $_GET['key'];
// Check if the key exists in the session
if(isset($_SESSION[$key])) {
  $file = $_SESSION[$key];
  // Remove the key from the session to prevent reuse
  unset($_SESSION[$key]);
  // Set the content type and headers for the file
  header("Content-Type: application/octet-stream");
  header("Content-Disposition: attachment; filename=" . basename($file));
  header("Content-Length: " . filesize($file));
  readfile($file);
  
}
else{
   echo("Invalid link");
}
?>

Every time the page is refreshed, it creates a new one-time link that can only be used once.

And if I follow this link, the file will be downloaded. But when I follow it a second time, the link is no longer valid. How can I make the link update when clicking on it (without refreshing the page), so that the link is always valid?

I do not know how to do it? How can this be done? Via ajax? Or how?


name
  • 7
  • 2

1 Answers1

0

Here you go:

<?php
    session_start();
    $file1 = "img/img1.jpeg";
    $key1 = md5($file1 . microtime());
    $_SESSION[$key1] = $file1;
    $link1 = "download.php?key=" . $key1;
    echo "<a href='" . $link1 . "'id='button1'>download</a><br>";

?>

download.php

<?php
session_start();
// Get the key from the query string
$key = $_GET['key'];
// Check if the key exists in the session
if(isset($_SESSION[$key])) {
  $file = $_SESSION[$key];
  // DO NOT remove the key from the session, to allow reuse
  //unset($_SESSION[$key]);
  // Set the content type and headers for the file
  header("Content-Type: application/octet-stream");
  header("Content-Disposition: attachment; filename=" . basename($file));
  header("Content-Length: " . filesize($file));
  readfile($file);
  
}
else{
   echo("Invalid link");
}
?>

It works now. :-)

(This answers your question, but if it's not what you wanted, you might need to be clearer about your objective and reasons.)

Michael G
  • 458
  • 2
  • 9