问题
I want to make a webpage which has download option for a pdf, but i want it password protected i.e. if someone clicks on that link he has to enter username and password and if he directly open the link "www.example.com/~folder_name/abc.pdf" then server ask for password first and then allow to download
Edit: I want user to view the file in browser, not to force it to download here is my code
<?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);
?>
but this code is not opening pdf in my browser. I don't want code to depend upon pdf plugin used by browser
回答1:
You can make a .htaccess
file in the web folder you have the download set up at so that before anyone can enter the domain, they have to enter the correct user and password to get in.
Here's a blog post that I used when I set up my own but essentially your .htaccess file will look like this:
AuthType Basic
AuthName "restricted area"
AuthUserFile /path/to/file/directory-you-want-to-protect/.htpasswd
require valid-user
You also need to create a .htpasswd
file where you can put a username and a password. The password needs to be encrypted with MD5 hash but you can use the generator he links to in his blog. Hope this helps.
回答2:
You can still use .htaccess
to not let anyone directly download your document and secure the link to the document instead.
.htaccess could be like this
RewriteRule ^([A-Za-z0-9-]+).pdf$ index.php [L,QSA]
And you can use php for that.
Somethink like this
<?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;
?>
来源:https://stackoverflow.com/questions/18605936/making-a-downloadable-file-password-protected-on-webpage