Reputation: 682
I would like to detect an array of strings in $_SERVER["SERVER_NAME"]
to define a constant for environment like dev/prod.
Basically, if localhost
or .dev
is in the URL, that would set the constant to "prod".
Here is my try but I always got "prod"
even if my current url is "localhost:3000" or "site.dev":
// Define environment
$dev_urls = array(".dev", "localhost");
if (str_ireplace($dev_urls, "", $_SERVER["SERVER_NAME"]) == $_SERVER["SERVER_NAME"]){
define("ENV", "dev");
} else {
define("ENV", "prod");
}
Finally used this code which works like a charm
// Define environment
$dev_urls = array(".dev", "localhost", "beta.");
if (str_ireplace($dev_urls, "", $_SERVER["HTTP_HOST"]) != $_SERVER["HTTP_HOST"]){
define("ENV", "dev");
} else {
define("ENV", "prod");
}
Upvotes: 3
Views: 415
Reputation: 27844
The SERVER_NAME
is defined in the server config, it never changes no matter what URL you use to reach that page.
I believe you want to use HTTP_HOST
instead.
if ($_SERVER['HTTP_HOST'] == 'localhost' || substr($_SERVER['HTTP_HOST'], -4) == '.dev')
define('ENV', 'dev');
else
define('ENV', 'prod');
Upvotes: 3