Reputation: 2110
I'm not a PHP programmer but I need to get the current file name and parent folder name when using an included script (require_once(myscript)
)
I know that basename(__DIR__)
and basename(__FILE__)
give me the info, BUT! from the running script, which in turn returns a different result e.g:
Consider the following folder structure:
/index.php
/other.php
/dir/util.php
if i have the function below in util.php
public static function echoParentAndFileNames(){
echo basename(__DIR__) . "<br />";
echo basename(__FILE__) . "<br />";
}
And I run the code bellow in index.php
require_once("dir/util.php");
Util::echoParentAndFileNames();
The output will be: dir and util.php and I want index.php and its parent folder name ...
So how can I call this script from an included file and have it show me the required info ?
Upvotes: 1
Views: 58
Reputation: 11689
To refer to current executing script you can use $_SERVER['SCRIPT_FILENAME']
.
So, you can change your function to:
public static function echoParentAndFileNames(){
echo basename( dirname( $_SERVER['SCRIPT_FILENAME'] ) ) . "<br />";
echo basename( $_SERVER['SCRIPT_FILENAME'] ) . "<br />";
}
From PHP Docs:
'SCRIPT_FILENAME'
The absolute pathname of the currently executing script.Note:
If a script is executed with the CLI, as a relative path, such as file.php or ../file.php, $_SERVER['SCRIPT_FILENAME'] will contain the relative path specified by the user.
Upvotes: 3