Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
371 views
in Technique[技术] by (71.8m points)

php - how to password protect downloadable pdf files in website

I am having a personal portfolio website and i have a some pdf files like

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

I dont want everyone to download the file, and i want it to protect it with password,so that i can share it with only the people i know

where only the person who gives the correct password is able to download my file

Note: 1. since its a personal portfolio website it do not have any "LOGIN's"
2. I have designed the webpage with HTML as a responsive code

Your suggestions please, any way of doing it without .htaccess ??

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You need to use a php file to feed the file through where the pdf files are stored in a NON PUBLIC folder.

For example, put your pdfs in a non public accessible directory, let's say: /home/pdfs/

And your PHP script in a public accessble directory, let's say: /home/public_html/

Inside the script in the public directory put:

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); 

Use GET values to determine the file to download, but to ensure better security only allow .pdf extensions, strip all other periods and slashes to prevent them from traversing the directories of your server and being given important security files containing passwords etc!!! To be even safer still only name your pdf files using characters a-z 0-9 and - or _

And then when you wish to download a file craft the correct URL to the script above, and ensure the pdf file exists in the non public directory.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...