Password protect list of links *and* password protect access to files
(I know this is probably a simple question to answer, but I don't know how to do it. Sorry if this has been asked before.)
What I want. I want a list of links to filse that are located on the server. The files are documents (pdf files). I understand how to use PHP to restrict access to the list of links, but one could just enter the direct link to the files in the browser and download the files. So I want to have the PHP file password protected (the list of links) and have people only enter the password once.
What I have. So far I have documents.php (found on the internet):
<?php
$username = "name";
$password = "5f4dcc3b5aa765d61d8327deb882cf99";
if ($_POST['txtUsername'] != $username || md5($_POST['txtPassword']) != $password) {
?>
<h1>Login</h1>
<form name="form" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<p><label for="txtUsername">Username:</label>
<br /><input type="text" title="Enter your Username" name="txtUsername" /></p>
<p><label for="txtpassword">Password:</label>
<br /><input type="password" title="Enter your password" name="txtPassword" /></p>
<p><input type="submit" name="Submit" value="Login" /></p>
</form>
<?php
}
else {
?>
<p>Link to documents</p>
<p><a href="http://example.com/folder/file.pdf">file.pdf</a></p>
<?php
}
?>
But with this a person could just access the file from the browser with the direct link: http://example.com/folder/file.pdf.
How do I prevent a this?
(I am comfortable开发者_如何学编程 with PHP and javascript and basic HTML) Thanks, Thomas
Mediate access to the files through php
Put the documents outside your webroot and keep a named array of the paths to them in your php file. When the client asks for a file by name (after you've authenticated them), look the file's path up in the array, and read the file from the filesystem, then output its contents back to them.
This is what readfile is designed for.
Similar to quasistoic's answer - except use your web server (eg. Apache or nginx) to provide a protected/internal URL for the PDF files (so not just a static URL within your webroot), and then use the X-Sendfile (or if on nginx the X-Accel-Redirect) header to send the file without having to stream the file through PHP.
精彩评论