Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
272 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...