tags:

views:

184

answers:

8

Hello

Is there a way to prevent user viewing an file but still use it as included to another file in php? Hope you understood!

Martti

+3  A: 

If you use

define('APP_RAN'); 

in the file that includes it and then put

if(!defined('APP_RAN')){ die(); }

in included files it would die if you access them directly.


It would probably be better to put all of your included files above your DocumentRoot though.

For example, if your index page is at

/my/server/domain/public_html

You should put the included files in

/my/server/domain/
Chacha102
This is the best solution, it's part of basic website protection.
Daan
Which one, defining or the path?
Martti Laine
Both, even if you can use only one.The path is easier to implement, the define will take some time to be implemented.
Daan
A: 

Just store the file outside your web root.

Erik
A: 

Under Apache, this is easy: add a <Files> directive in your .htaccess to prevent access to it from a web browser. This doesn't apply to PHP includes, and it is a good practice to hide several files from browser access (though usually you'll try to put all the non-accessible files together in a single directory).

<Files="myprivatefile.php">
    deny from all
</Files>

Under a different web server, you can hide the file out of your document root, but under some cases (like if your scripts are open_basedir'd in a strict way), it won't work.

zneak
A: 

You have to use an Encoder and Loader PHP extension:
Commercial:
http://www.ioncube.com/
http://www.zend.com/en/products/guard/
http://www.phpshield.com/ and http://www.sourceguardian.com

Free:
http://eaccelerator.net/
http://ombudi.com/

Pseudo (may be useful, not a true encoder):
http://www.raizlabs.com/software/phpobfuscator/

clyfe
+3  A: 

do not use any global code in your files, only functions and methods - and there will be no need to care about include vs. direct use.

stereofrog
Agreed; if anyone manages to guess the name of your include file that has only functions and classes, all they'd see is a blank page when trying to view it. If you're outputting html with an include (which I don't like to do) you can instead put it into a function, include the file, and call the function.
Alex JL
A: 
Daan
+1  A: 
if (__FILE__ == $_SERVER['PHP_SELF']) die("Direct access forbidden");
Col. Shrapnel
A: 

If you want to stop it from ever being displayed when not included here's a more automated way.

if (basename(__FILE__) == basename($_SERVER['PHP_SELF'])) header("HTTP/1.0 404 Not Found");

This way it'll still work if you end up changing the file name or something.

ZeekDaGeek