开发者

How to set up an env variable in PHP?

I'm trying to set up a enviroment variable in my website.

The idea is to creat a $env='test'; or $env='production'; and all the other PHP files, check this var to see in which env they are.

The soluti开发者_如何学运维on that I will work now is creating a session in the index file. But I dont feel confortable with this solution.


The best way to do it is to set your environnements variables inside your... environnement.

If you use Apache, you can add this inside your virtual host configuration (or .htaccess):

SetEnv MYAPP_ENV value

Then, inside your PHP:

$_SERVER['MYAPP_ENV']

There is SetEnv equivalent for all the web servers you can find.


you can use putenv

putenv("KEY=VALUE");


you can use the declare method in your index file for example;

define('env', 'production');
//check for env
function isEnv($env = 'production')
{
  return defined(env) && $env == env;
}
//now use our function
if(isEnv('dev'))
//do something here


Use php sessions or cookies.


Have you looked at get_cfg_var()? It allows you to set something in php.ini, and call it (unlike ini_get(), which doesnt seem to grab custom variables in php.ini)

I needed to do something similar, and this was able to do it for me.


Recently i wrote a library to get values from environment variables and parse to the PHP data types. This library can be used to parse environment variables to PHP data types (like the casting to integer, float, null, boolean), parse the complex data structures like a JSON string and more with the contribution of the commnunity.

The library is available here: https://github.com/jpcercal/environment

Setup your environment variables with .htaccess file in a directory named "www" or "htdocs" or "public" or "web" depend of your hosting company. The content of .htaccess:

...
SetEnv APP_ENV production
...

And to get the values from environment variable (independently of the environment CLI, Apache, Nginx, PHP Built-in Server and more) to do it:

<?php
// ...
require "vendor/autoload.php";
// ...
if (Cekurte\Environment\Environment::get("APP_ENV") === "production") {
    // ...
    // It is your production environment ...
} else {
    // ...
    // It is your development environment ...
}

Enjoy it.


  1. define your variable in server(s). for linux write:
export DEVELOPMENT=1

or

export PRODUCTION=1

or smth else (TEST/STAGING etc.)

  1. test step 1 - write in console:
env

or

env | grep DEVEL

or

env | grep PROD

etc.

  1. use getenv() in your code. 4 example:
if (!empty(getenv('DEVELOPMENT'))) {
    echo 'ello Creator';
}

now you can get different behavior by using common code.


PHP provides the array: $GLOBALS to store variables at global scope.

e.g.

//to set the variable:
$GLOBALS["env"] = "test";
//to access the variable:
$some_var = $GLOBALS["env"];

More here: http://php.net/manual/en/reserved.variables.globals.php

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜