Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: Check if a file is loaded directly instead of including?

Tags:

file

include

php

Is there a way to prevent a user viewing an file but still use it as included to another file in PHP?

like image 890
Martti Laine Avatar asked Mar 07 '10 16:03

Martti Laine


2 Answers

If you use

define('APP_RAN');  

in the file that includes it and then put

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

or alternatively

defined('APP_RAN') or die(); 

(which is easier to read)

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/ 
like image 66
Tyler Carter Avatar answered Sep 20 '22 05:09

Tyler Carter


My proposal:

<?php if (__FILE__ == $_SERVER['SCRIPT_FILENAME']) {     header($_SERVER['SERVER_PROTOCOL'] . ' 404 Not Found');     exit("<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\r\n<html><head>\r\n<title>404 Not Found</title>\r\n</head><body>\r\n<h1>Not Found</h1>\r\n<p>The requested URL " . $_SERVER['SCRIPT_NAME'] . " was not found on this server.</p>\r\n</body></html>"); } else {    // your code } ?> 

1.) it checks if it is called directly else it throws an error

2.) it outputs a 404 standard apache error page (please compare with your original 404 page or simple include that page) to add security through obscurity

3.) The else-part avoids partial execution while the file is uploaded to the live environment (PHP doesn't wait for the "?>"). You don't need it if your included file contains only one function / one class.

like image 25
mgutt Avatar answered Sep 19 '22 05:09

mgutt