3

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.

4 Answers 4

4

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';
Sign up to request clarification or add additional context in comments.

Comments

2

Use " will parse the variable.

"/directory1/$dir2/directory3/file.php"

And instead of depending $_SERVER['DOCUMENT_ROOT'], you should do something like diranme(__FILE__) or __DIR__ (>= 5.3) to define a root dir.

Comments

2

There are two ways to do this in PHP.

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

Or

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

The difference is in using ' or " for strings. When using ' You need to concatenate variables as in the example and as You already did with $_SERVER['DOCUMENT_ROOT']. When using ", You can put the variables in strings "as is" or even do something like this (useful with arrays):

require_once $_SERVER['DOCUMENT_ROOT'] . "/directory1/{$_SERVER["HTTP_HOST"]}/directory3/file.php";

Comments

1

Single quotes prevent variable substitution. Use double quotes:

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

Comments

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.