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.

martin
  • 393
  • 1
  • 6
  • 21

4 Answers4

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';
Marc B
  • 356,200
  • 43
  • 426
  • 500
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";
Najki
  • 514
  • 6
  • 22
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.

xdazz
  • 158,678
  • 38
  • 247
  • 274
1

Single quotes prevent variable substitution. Use double quotes:

require_once $_SERVER['DOCUMENT_ROOT'] . "/directory1/$dir2/directory3/file.php";
Alex Howansky
  • 50,515
  • 8
  • 78
  • 98