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

时间:2013-09-04 05:22:11

标签: php javascript html5 password-protection

我想制作一个有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插件

2 个答案:

答案 0 :(得分:1)

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

这是我在设置自己时使用的blog post,但基本上你的.htaccess文件将如下所示:

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

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

答案 1 :(得分:0)

您仍然可以使用.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;
?>