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

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


Solution 1:

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/

Solution 2:

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.

Solution 3:

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