When execution a script that includes a library, I whant to find from whithin the library the caller script, in Perl I'm using env: $0 that gives me the path to the caller script. In PHP __FILE__ gives me the current script, so in the library it gives me the library path not the caller script path.
from perl documentation: $0 Contains the name of the file containing the Perl script being executed.
I think It can be done using debug_backtrace(), but there is another better/shorter method ?
EDIT: (added sample code)
file: index.php
<?php
require 'locallib.php';
echo 'in original script = '.__FILE__.'<br />';
?>
file: locallib.php
<?php
require "lib.php";
echo 'in library "'.__FILE__.'"<br />';
?>
file: lib.php
<?php
if( $_SERVER['SCRIPT_FILENAME'] != '/var/www/html/index.php')
{
echo "Not allowed";exit;
} else
{
echo 'in library "'.__FILE__.'"<br />';
echo '<pre>';
print_r($_SERVER);
echo '</pre>';
}
?>
The $_SERVER array is not set when calling a PHP script from the console.
The only way I found of making it work both in web pages and console scripts was with this function:
function php_self(){
$bt = debug_backtrace();
return $bt[count($bt)-1]['file'];
}
$_SERVER['SCRIPT_FILENAME'];
$_SERVER reference.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With