0

I have this code snippet that includes a subpage:

function getTabFile($pageName) {
    if ($pageName == null)
        return null;
    if (preg_match("/^[a-z]+$/i", $pageName) != 1)
        return null;
    $fileName = getTabFileName($pageName);
    if (file_exists($fileName))
        return $fileName;
    return null;
}
function getDefaultTabFile() {
    return getTabFileName('default');
}
function getTabFileName($page) {
    return __DIR__ . "/page/$page.php";
}
include (getTabFile($_GET['page'] ?? null) ?? getDefaultTabFile());

And I want this snippet itself to be included via:

$path = $_SERVER['DOCUMENT_ROOT']; 
$path .= "/common/snippet.php"; 
include($path);

When I do this the script targets the relative DIR of where the snippet is located.

My question is: Is it possible to target the relative DIR of the file where the snippet is included?

5
  • Does this answer your question? Running a php file from another php file as if I opened it directly from the browser (relative path issue) Commented Mar 11, 2022 at 20:01
  • Effectively, to ensure your application is compatible in different environments, you would not rely on $_SERVER['DOCUMENT_ROOT'] in favor of using require_once __DIR__ . '/common/snippet.php'; or specify the relative pathing based on the calling script file's depth eg: $_SERVER['DOCUMENT_ROOT']/subdir/nested/script.php would use require_once __DIR__ . '/../../common/snippet.php'; Commented Mar 11, 2022 at 20:26
  • Thanks for the suggestion, but it doesn’t really work for me like that, since I need this script to work no matter in which subfolder file it is included. I would have to find a solution where it isn’t needed to backtrack manually to the root directory. But also, I’m a noob with PHP so maybe I just didn’t get you. Commented Mar 11, 2022 at 21:05
  • Correct. What you're after isn't possible since you need to tell PHP where the file resides and the way include works with relative pathing. The most reliable method is to specify from the executing script where the include file is located using absolute paths __DIR__ . '/../path/to/script.php', otherwise you end up running into very quirky behavior. A workaround would be to specify the directory your include file resides using set_include_path, then exclude the path, but you will run into other ambiguous issues. Commented Mar 11, 2022 at 21:13
  • For clarification return __DIR__ . "/page/$page.php";, where __DIR__ will ALWAYS be the directory of that script file only. So in your example __DIR__ will always be /var/www/common, resulting in /var/www/common/page/default.php as the return value. Commented Mar 11, 2022 at 21:19

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.