View Full Version : protecting files in a folder

09-14-2005, 07:09 PM

I don't know what my question is called, so i couldnt search for it, so if i'm repeating a question, i'm sorry, you can just point me to the answer....

I have a site where users have a username and passord using sessions. Once they log in, they can download .pdf's from my server.

What I would like is to protect my folder where all the .pdf's are located without using .htaccess, because then the user's going to have to re-enter a username and password once they click on the .pdf.

What are my options? (i don't want people to just type in the location of the .pdf's in their address bar and download them)

Thank you

09-14-2005, 08:44 PM
Well, if it were me, I'd not put the pdfs in a directory visible on the web at all.
I'd stream them to the browser, like I do with my C# and java stuff.
(file download instead of just a link)

09-14-2005, 09:21 PM
how do u do that?

09-14-2005, 09:52 PM
Not that sure, actually. :o
I could post the C# code if it helps you...

09-14-2005, 10:06 PM
I'd stream them to the browser

how do i do that?

09-14-2005, 10:14 PM
Not sure if this exactly what you need, but I'm working on something similar and this is what i have so far:

link page:

<a href="downloadPdf.php?f=filename&t=pdf&s=<?=session_id()?>"> PDF Link </a>


function strrrchr($haystack,$needle) {
// Returns everything before $needle (inclusive).
return substr($haystack,0,strpos($haystack,$needle)+1);

$sn = $_GET["sn"];
if ($sn == session_id()) {
$fileName = $_GET["f"];
$fileExt = $_GET["t"];
$downloadFile = strrrchr($PATH_TRANSLATED,"/public_html")."downloads/".$fileName.".".$fileExt."";
} else {
$downloadFile = strrrchr($PATH_TRANSLATED,"/public_html")."downloads/unauthorized.pdf";
Header( "Content-Length: ".filesize($downloadFile));
Header( "Connection: close");
Header( "Accept-Ranges: bytes");
Header( "Content-Type: application/pdf");

So, basically I send the session id in the query string to the download, and make sure the query string and actual session id match on the download page. I have the files outside of my root web folder, which is what the "strrrchr($PATH_TRANSLATED...." line is doing, getting the real folder location, stripping it to the '/' before my public_html web root folder, then appending my download folder location.

I'm also sending the file name and extension so that ultimately, the page can handle any download, not just PDFs, but I haven't got that far yet (as far as the header content-type, the dynamic file name is working.)

Also, I've literally only just started on this and this works great in Firefox - not tested in IE or on a Mac yet though.

Hope this is useful, and makes sense ;)


09-14-2005, 11:41 PM
Go with his stuff. :D

We use Windows authentication for our C# stuff, so his PHP code has a lot more of what you need in there.
The C# code I have is half that size and doesn't need to check anyone's logins. .NET handles that.