安全的直接文件下载PHP需要修复

时间:2018-02-22 00:18:24

标签: php

不幸的是,这段代码无效,因为我想通过php下载文件,需要隐藏我服务器上传文件的直接路径。

如果我在变量.. example.com/files/filedownload.iso 中定义完整路径,那么它正在工作,但它没有意义,因为我想在下载时隐藏路径。

<form target="_blank" id="download_file" action="download.php" method="post">
<input name="ip" type="hidden" value="192.123.23.1">
<input name="filename" type="hidden" value="filedownload.iso"'; ?>
<div align="center">
<input alt="Submit" src="download.gif" type="image" />
</div>
</form>

上面的代码是POST方法..

<?php
  if(isset($_POST['ip']) && $_POST['ip']!="" && isset($_POST['filename']) && $_POST['filename']!=""){
    $filename = $_POST['filename'];
    }

    $domain="http://example.com/".$filename;
    //$redirect_url="http://example.com".$filename;
    $redirect_url=$path;
    $redirect_url= encrypt_download_link($domain,$path);

  ?>

   <script type="text/javascript">   
    var max_time= 5; //Seconds
    function Redirect() 
    {  
    window.location="<?php echo $redirect_url; ?>"; 
    }
    function refresh_remaining_time()
    {   
        max_time = max_time-1;
        if (max_time>=0) {
            document.getElementById("waiting_time_span").innerHTML = max_time+" Seconds";
        }
    }
    window.onload = function() {
        setInterval(function () {
            if (max_time>=0) {
                refresh_remaining_time();
            }
        }, 1000); // Execute somethingElse() every 2 seconds.
      setTimeout(function () {
            Redirect();
      }, 5000);
    };
    </script>

<?php
  }
  function encrypt_download_link($domain,$path){
    $secret = '4rTyHHgtopSUm';
    $expire = strtotime("+7 days");
    $md5 = base64_encode(md5($secret.$path.$expire,true));
    $md5 = strtr($md5, '+/', '-_');
    $md5 = str_replace('=', '', $md5);
      $url = $domain.$path."?st=".$md5."&e=".$expire;
      return $url;
  }
?>

1 个答案:

答案 0 :(得分:1)

我不确定这是否适合您,并且它不适用于大型文件,但如果您将用户重定向到具有此代码的页面,它会将文件以二进制形式传输到他们的系统。如果您的文件较大且不起作用,请不要讨厌。)

P.S。我很乐意为此而感到荣幸,并且我搜索了源代码(找不到它),但是几年之后,这会在别人的建议下打到我的图书馆。

$nameFile = 'insert just name of file here'
$pathFile = 'insert file and path here';
$sizeFile = filesize($pathFile);
$pointerFile = fopen($pathFile, "rb"); // Open file for reading in binary mode
$contentFile = fread($pointerFile, $sizeFile);
fclose($pointerFile);

header("Content-length: ".$sizeFile);
header("Content-type: application/octet-stream");
header("Content-disposition: attachment; filename=".$nameFile.";" );
echo $contentFile;