When using the PHP
include, how can I find out which file is calling the
include? In short, what is the parent's file filename?
When using the PHP
It seems nothing is concrete in the world of xhr. I therefore resulted to using the
X-File-Name header if I found it but requiring a user submitted filename. Uploads are read from the input stream.
Make sure you always include with an absolute path, like:
require_once(dirname(__FILE__) . "/otherfile.php"); require_once(dirname(__FILE__) . "/../uponefolder.php"); require_once(dirname(__FILE__) . "/sub/folder/file.php");
Or use autoloading.
The easiest way for the generic "PHP app running on an Apache server that you may or may not fully control" situation is to put your includes in a directory and deny access to that directory in your .htaccess file. To save people the trouble of Googling, if you're using Apache, put this in a file called ".htaccess" in the directory you don't want to be accessible:
Deny from all
If you actually have full control of the server (more common these days even for little apps than when I first wrote this answer), the best approach is to stick the files you want to protect outside of the directory that your web server is serving from. So if your app is in
/srv/YourApp/, set the server to serve files from
/srv/YourApp/app/ and put the includes in
/srv/YourApp/includes, so there literally isn't any URL that can access them.
You can't include php files relatively to your webroot that way, cause if you use the slash as first character, the reference will go much deeper than just your document root. So, instead of using your basepath, you could do something like this :
<?php $path = $_SERVER['DOCUMENT_ROOT']; $path .= "/yourpath/yourfile.php"; include_once($path); ?>
An easy way is to assign a variable in the parent file (before the inclue), then reference that variable in the included file.
You could also mess around with
debug_backtrace()and find the event when and where the file got included, but that can get a little messy and complicated.