Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
262 views
in Technique[技术] by (71.8m points)

php - 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?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...