Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get calling file name from include()

I want to get the name of the file that includes another file from inside the included file.

I know there is the __FILE__ magic constant, but that doesn't help, since it returns the name of the included file, not the including one.

Is there any way to do this? Or is it impossible due to the way PHP is interpreted?

like image 510
Jon Egeland Avatar asked Apr 22 '12 04:04

Jon Egeland


1 Answers

So this question is pretty old, but I was looking for the answer and after leaving here unsatisfied, I came across $_SERVER['SCRIPT_FILENAME']; Of course this works if the php file doing the including is a web page.

This gives you the full path of the "including file" on the server. eg /var/www/index.php. so if you want just the filename, eg index.php, you will need to use basename() eg

basename($_SERVER['SCRIPT_FILENAME']);

So, if in your index.php you have the following line:

<?php include("./somephp.php"); ?>

and in somephp.php you have

echo "this is the file that included me: " . basename($_SERVER['SCRIPT_FILENAME']);

you will get

this is the file that included me: index.php

output to the browser. This also works if the user is accessing your file without explicitly including the filename in the url, eg www.example.com instead of www.example.com/index.php.

like image 103
gnac Avatar answered Oct 05 '22 08:10

gnac