在网页上设置可下载文件的密码保护


Making a downloadable file password protected on webpage

我想制作一个有pdf下载选项的网页,但我希望它受到密码保护,即如果有人点击该链接,他必须输入用户名和密码,如果他直接打开链接"www.example.com/~folder_name/abc.pdf",则服务器首先询问密码,然后允许下载

编辑:我希望用户在浏览器中查看文件,而不是强制下载这是我的代码

<?php
    /* authentication script goes here*/
    $file = 'http://example.com/folder_name/abc.pdf';
    //header('Content-Description: File Transfer');
    header('Content-Type: application/pdf');
    header('Content-Disposition: inline; filename=' . basename($file));
    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($file));
    header('Accept-Ranges: bytes');
    @readfile($file);
?>

但这段代码无法在我的浏览器中打开pdf。我不希望代码依赖于浏览器使用的pdf插件

您可以在设置下载的web文件夹中创建一个.htaccess文件,这样在任何人进入域之前,他们都必须输入正确的用户和密码才能进入。

这是我在建立自己的.htaccess文件时使用的一篇博客文章,但本质上你的.htacccess文件是这样的:

AuthType Basic
AuthName "restricted area"
AuthUserFile /path/to/file/directory-you-want-to-protect/.htpasswd
require valid-user

您还需要创建一个.htpasswd文件,在其中可以放置用户名和密码。密码需要用MD5散列加密,但你可以使用他在博客中链接的生成器。希望这能有所帮助。

您仍然可以使用.htaccess不让任何人直接下载您的文档,而是保护到文档的链接。

.htaccess可以像这个

RewriteRule ^([A-Za-z0-9-]+).pdf$ index.php [L,QSA]

您可以使用php来实现这一点。

有点像

<?php
    //here you authenticate user with your script
    //and then let the user download it
    if (!isset($_SESSION['authenticated']))
    {
       header('Location: http://www.example.com/');
       exit;
    }
    $file = 'www.example.com/~folder_name/abc.pdf';
    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, post-check=0, pre-check=0');
    header('Pragma: public');
    header('Content-Length: ' . filesize($file));
    ob_clean();
    flush();
    readfile($file);
    exit;
?>