Reputation: 485
Anyone can help me get the basename of directory where the function called? I mean:
file /root/system/file_class.php
function find_file($dir, $file) {
$all_file = scandir($dir);
....
}
function does_exist($file) {
$pathinfo = pathinfo($file);
$find = find_file($pathinfo["dirname"], $pathinfo["basename"]);
return $find;
}
file /root/app/test.php
$is_exist = does_exist("config.php");
Under /root/app i have file "config.php, system.php". Do you know how to get the directory where does_exist()
called? In function find_file()
argument $dir
is important, since scandir()
function need directory path to scaned. I mean, when i want to check file config.php
i doesn't need to write /root/app/config.php
. If i not provide fullpath in $file
argument, the $pathinfo["dirname"] will be "."
. I've try to use dirname(__file__)
in file_find()
function but it's return the directory /root/system
not /root/app
where it is the directory of does_exist()
function called.
I need create those function since i can't use file_exists()
function.
Found Solutions:
I'm using debug_backtrace()
to get the recent file and line number of where users calling function. For example:
function read_text($file = "") {
if (!$file) {
$last_debug = next(debug_backtrace());
echo "Unable to call 'read_text()' in ".$last_debug['file']." at line ".$last_debug['line'].".";
}
}
/home/index.php
16 $text = read_text();
The sample output: Unable to call 'read_text()' in /home/index.php at line 16.
Thanks.
Upvotes: 1
Views: 1220
Reputation: 4946
Use any of PHP magic constants
__DIR__
__FILE__
http://php.net/manual/en/language.constants.predefined.php
Or use realpath("./");
To define your own constant paths:
define("MYPATH", realpath("./") . "/dir/dir/";
You can then call this MYPATH from everywhere this code (file) is included.
Upvotes: 1