bodacydo
bodacydo

Reputation: 79309

How do I dynamically include a PHP script?

I'm writing code in PHP that requires including a config.php file depending on the website URL.

I've the website URL in the variable $site, and the config for $site is in the directory configs/$site/config.php.

How can I require this file dynamically in PHP?

Is it safe to do include "configs/$site/config.php";?

Upvotes: 0

Views: 68

Answers (2)

KingCrunch
KingCrunch

Reputation: 131861

If you limit $site to a set of values, yes.

$sites = array(
  'siteA',
  'siteB'
);
if (isset($sites[$site])) {
  include "configs/$site/config.php";
} else {
  throw new Exception("Unknown site");
}

But remember: Never trust anything from outside, always validate values, that come from a client (browser).

Upvotes: 7

sachleen
sachleen

Reputation: 31131

That is fine. Just make sure the $site variable cannot be changed by the user! If the user can change it, he can make it include any file.

Upvotes: 0

Related Questions