Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Php - get parent-script name

Tags:

php

parent

parent.php:

require_once 'child.php';

child.php:

echo __FILE__;

It will show '.../child.php'

How can i get '.../parent.php'

like image 762
Max Frai Avatar asked Aug 23 '09 13:08

Max Frai


People also ask

What is the best way to get the filename of the current running script?

Since we are using PHP, we can easily get the current file name or directory name of the current page by using $_SERVER['SCRIPT_NAME']. Using $_SERVER['SCRIPT_NAME']: $_SERVER is an array of stored information such as headers, paths, and script locations.

How can we find out the name of the current executing file in PHP?

php $current_file_name = basename($_SERVER['PHP_SELF']); echo $current_file_name.

How do I go back to a parent directory in PHP?

If you are using PHP 7.0 and above then the best way to navigate from your current directory or file path is to use dirname(). This function will return the parent directory of whatever path we pass to it.

How to include file path in PHP?

PHP Include Files. The include (or require ) statement takes all the text/code/markup that exists in the specified file and copies it into the file that uses the include statement. Including files is very useful when you want to include the same PHP, HTML, or text on multiple pages of a website.


3 Answers

The chosen answer only works in environments that set server variables and specifically won’t work from a CLI script. Furthermore, it doesn't determine the parent, but only the topmost script file.

You can do almost the same thing from a CLI script by looking at $argv[0], but that doesn’t provide the full path.

The environment-independent solution uses debug_backtrace:

function get_topmost_script() {
  $backtrace = debug_backtrace(
      defined("DEBUG_BACKTRACE_IGNORE_ARGS")
      ? DEBUG_BACKTRACE_IGNORE_ARGS
      : FALSE);
  $top_frame = array_pop($backtrace);
  return $top_frame['file'];
}
like image 104
danorton Avatar answered Nov 16 '22 01:11

danorton


print $_SERVER["SCRIPT_FILENAME"];
like image 21
Sampson Avatar answered Nov 16 '22 00:11

Sampson


I don't think you can do that : the __FILE__ magic constant indicates in which file it is written ; and that is all.

If you want to know which PHP script was initially called (which URL was requested, for instance), you might have more luck looking at the $_SERVER superglobal : it contains many informations, including some that will help you (like SCRIPT_FILENAME or SCRIPT_NAME, for instance) ;-)

like image 27
Pascal MARTIN Avatar answered Nov 16 '22 00:11

Pascal MARTIN