Search code examples
phprequire-once

Variable in php require_once file path


How do you take the following and substitue part of the file path as a variable?

require_once $_SERVER['DOCUMENT_ROOT'] . '/directory1/directory2/directory3/file.php';

I want to substiture directory2 with a variable $dir2. Simply inserting the variable as follows does not work?

require_once $_SERVER['DOCUMENT_ROOT'] . '/directory1/$dir2/directory3/file.php';

Thanks.


Solution

  • Basic php syntax: strings quoted with ' do not interpolate variables. Use a "-quoted string instead:

    require_once $_SERVER['DOCUMENT_ROOT'] . "/directory1/$dir2/directory3/file.php";
                                             ^---                                  ^---
    

    or use string concatenation:

    require_once $_SERVER['DOCUMENT_ROOT'] . '/directory1/' . $dir2 . '/directory3/file.php';