如何生成动态网址以防止直接下载?

时间:2016-05-07 07:38:25

标签: php

我想为我的网站生成一个下载网址,目前就像this,但可以直接访问我不希望有人复制粘贴链接,然后直接开始下载,我通过电子邮件发送下载链接。

3 个答案:

答案 0 :(得分:2)

您可以创建一个脚本,告诉PHP提供该文件。这是我之前从SO获得的一个很棒的功能:

<强>的download.php

function send_download($file){
    $basename = basename($file);
    $length   = sprintf("%u", filesize($file));

    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename="' . $basename . '"');
    header('Content-Transfer-Encoding: binary');
    header('Connection: Keep-Alive');
    header('Expires: 0');
    header("Accept-Ranges: bytes");
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    header('Pragma: public');
    header('Content-Length: ' . $length);

    set_time_limit(0);
    ob_get_clean(); 
    readfile($file);
    ob_end_flush(); 
}

$file="file/download/path";
send_download($file);

所以你的下载链接如下:

something.com/download.php?id=some_hash_or_id

答案 1 :(得分:1)

1:不要给用户直接链接到文件。将这些文件放在受.htaccess保护的单独文件夹中。例如:将所有文件放到名为“User_Files”的目录中,然后生成此.htaccess文件:

deny from all

因此用户无法直接访问此文件。

2:创建一个php脚本,向用户读取文件。您可以在读取文件之前进行会话或登录检查,如下所示:

if (isset($_SESSION['logged_in']) AND $_SESSION['logged_in'] == 1){ //change it to suit your needs to verify whatever you want before reading file to user
    $file = "Files/something.rar";
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename='.basename($file));
    header('Content-Transfer-Encoding: binary');
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: ' . filesize($file));
}

因此,当用户访问http://yourdomain.com/your_script.php时,PHP会将文件读取给用户。

答案 2 :(得分:0)

  <?php

  //start session
  session_start();

  function randomkey( $length ) {
      $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
      return substr(str_shuffle($chars),0,$length);
  }

  //if the session exist
  if(isset($_SESSION['sessionid'])){

        //check session id 
    if($_SESSION['sessionid'] == $_GET['sessionid']){
        echo 'Download script here! for file :' . $_GET['fileid'];
        session_destroy(); //to avoid reapply for download

      }else{ //if user has provided false sessions.
        echo 'Redirect user to the page again!'; 
        session_destroy(); //to avoid reapply for download
      }

  }else{

      //if session not exist

  //create a temporary session
  $sessionid = randomkey(20);
  $_SESSION['sessionid'] = $sessionid;

  ?>
  <form action="" method="get">
      <input type="hidden" name="sessionid" value="<?php echo $sessionid ?>">
      <input type="hidden" name="fileid" value="File you want the user to download">
      <input type="submit" value="download">
  </form>

  <?php

  }

  ?>