Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

find caller script path from a library

Tags:

php

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>';
}
?>
like image 401
Radu Maris Avatar asked Mar 24 '26 10:03

Radu Maris


2 Answers

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'];
}
like image 126
Sebastián Grignoli Avatar answered Mar 26 '26 00:03

Sebastián Grignoli


$_SERVER['SCRIPT_FILENAME'];

$_SERVER reference.

like image 29
Ionuț G. Stan Avatar answered Mar 25 '26 23:03

Ionuț G. Stan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!