首页 文章

如何在网站上保护可下载的pdf文件的密码

提问于
浏览
5

我有一个个人投资组合网站,我有一些像pdf文件

<a href="file.pdf">Some file</a>

我不希望每个人都下载该文件,我希望它用密码保护它,以便我只与我认识的人分享

只有提供正确密码的人才能下载我的文件

注意:1 . 由于它是个人投资组合网站,它没有任何"LOGIN's"
2.我将网页设计为HTML作为响应代码

请你的建议,没有.htaccess的任何方式吗?

4 回答

  • 3

    使用MySQL或MySQLite - 取决于您的偏好 - 并将链接存储到数据库中的PDF . 然后使用download.php等脚本 . 在文件数据库中存储该文件的密码,并要求用户在下载文件之前输入该密码 . 如果您不熟悉数据库,您可以在PHP中完成所有操作 .

    一个非常粗略的模型(没有数据库,如果你熟悉dbs,相应调整)

    HTML表单

    <form name="download" id="download" method="post" action="download.php">
      <input type="password" id="password" name="password" />
      <input type="submit" id="submit" value="Download" />
    </form>
    

    PHP(download.php)

    <?php
         // Get the password
              $pw = md5($_POST['password']);
    
         // Compare against the stored password
              $valid_pw = md5("your password you want to use");
    
              if($pw != $valid_pw){
                   echo "Error! You do not have access to this file";
              }else{
                   header("Location: /path/to/your/file.pdf");
              }
    ?>
    

    笔记:

    我使用了一种非常基本的加密密码的方法 . 如果这是我的应用程序,我会研究更好的方法,但为了简洁和易于理解,我使用了一个简单的 md5() 哈希比较 .

  • 4

    您需要使用php文件来提供文件,将pdf文件存储在NON PUBLIC文件夹中 .

    例如,将您的pdf放在非公共可访问目录中,假设:/ home / pdfs /

    并且您的PHP脚本位于公共可访问目录中,例如:/ home / public_html /

    在公共目录中的脚本里面放了:

    if (isset($_GET('password')) {
    die('wrong password');
    }
    
    if ($_GET['password'] != 'mypass') {
    die('wrong password');
    }
    
    $file="/home/pdfs/test.pdf";
    header("Pragma: public");
    header('Content-disposition: attachment; filename='.$file);
    header("Content-type: ".mime_content_type($file));
    header('Content-Transfer-Encoding: binary');
    ob_clean();
    flush();
    readfile($file);
    

    使用GET值来确定要下载的文件,但是为了确保更好的安全性,只允许.pdf扩展,删除所有其他句点和斜杠以防止它们遍历服务器的目录并获得包含密码等的重要安全文件!为了更安全,仍然只使用字符a-z 0-9和 - 或_命名你的pdf文件

    然后,当您希望下载文件时,请使用上述脚本的正确URL,并确保pdf文件存在于非公共目录中 .

  • 1

    按照 @rsmith84's 提示,但请确保阻止文件夹访问:

    Apache .htaccess文件

    Deny from all
    

    IIS web.config文件

    <system.webServer>
        <security>
            <authorization>
                <remove users="*" roles="" verbs="" />
                <add accessType="Allow" roles="Administrators" />
            </authorization>
        </security>
    </system.webServer>
    

    然后允许仅使用PHP文件传递 . 验证用户,然后从受保护的文件夹中执行 readfile('/protectd/file/path') .

  • 2

    创建一个php文件,例如 download.php 并链接到该文件 .
    您可以在那里检查密码是否正确,如果正确,您可以将PDF文件的内容写入响应 .

相关问题