views:

26

answers:

2

Hello,

I've been wondering: is it possible to shield a directory/file on a server from the outside world, but make it accessible to PHP?

It's fairly simple. I'm caching webpages on my server with PHP in a certain directory, but I do not want web users to view these files or this directory directly. PHP, on the other hand, must be able to access these files (to serve them to the user). That may sound not logical, but what I'm trying to do is restrict users certain pages and still be able to cache them in a webserver-savvy format.

Preferably something with .htaccess or chmod.

Thanks!

+5  A: 

Absolutely-- in fact, you don't need to use .htaccess. Simply put the protected directory above your document root (that is, store it next to the folder where your PHP scripts are store, typically "htdocs," "httpdocs" or sometimes just "www').

So your web files would be in /my/folders/httpdocs/, and your "protected" files would be in /my/folders/protected_folder/

The idea here is that PHP can access any folder on the server, but Apache won't let the user navigate "above" the root directory.

To access the directory, you can use:

$protected_path = $_SERVER['DOCUMENT_ROOT'].'/../protected_folder/';

(Incidentally, you mentioned you're doing this to cache pages-- you might want to look at Smarty, the PHP template engine, which pre-compiles your templates and also supports really smart caching. And in fact, one of the Smarty "best practices" is to configure your structure so the template and cache files are not in or below the document_root folder, so users coming in from Apache can never get to them, but the Smarty PHP code can easily grab whatever it needs from there.)

Eric
Excellent! Thanks a lot, its a very smart solution.
Reinder de Vries
My pleasure... good luck with your project.
Eric
+2  A: 

Sure, just place the files in a directory outside of your web root. For instance, if your web root is /usr/local/apache/htdocs/ you can create a /usr/local/apache/private_cache/ directory that PHP should have access to, but there is no way to get to it via a web request.

You can also put a .htaccess file consisting of the line deny from all in the directory you want to protect. That will prevent Apache (but not PHP) from serving up the files.

Frank Schmitt