In PHP, how can I get the directory of a patent script in an included script?
In PHP, you can use the __DIR__
magic constant to get the directory of the current script, and debug_backtrace()
function to get the directory of the parent script (the script that included the current script).
Here's an example:
parent_script.php
:
php
<?php
// Include the child script
include 'child_script.php';
child_script.php
:
<?php
// Get the directory of the current script (child_script.php)
$childScriptDirectory = __DIR__;
echo "Child script directory: $childScriptDirectory\n";
// Get the directory of the parent script (parent_script.php)
$parentScriptPath = $_SERVER['SCRIPT_FILENAME'];
$parentScriptDirectory = dirname($parentScriptPath);
echo "Parent script directory: $parentScriptDirectory\n";
When you run parent_script.php
, the output will show the directories of both the child and parent scripts.