tags:

views:

27

answers:

2

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>';
}
?>

@Ionuț G. Stan was right $_SERVER['SCRIPT_FILENAME'] is what I was looking for, as you saw I nested 3 scripts with require and it works.
@Unicron what did you mean with "Doesn't work if there are nested includes" ?

+1  A: 
$_SERVER['SCRIPT_FILENAME'];

$_SERVER reference.

Ionuț G. Stan
+1 works for the main caller script. Doesn't work if there are nested includes, but AFAIK, nothing will work for those - not even a backtrace.
Unicron
A: 

Did you try either of these:

$_SERVER['SCRIPT_FILENAME'];
$_SERVER['PHP_SELF'];
Sarfraz