Check for environment variable php

$_ENV

An associative array of variables passed to the current script via the environment method.

These variables are imported into PHP’s global namespace from the environment under which the PHP parser is running. Many are provided by the shell under which PHP is running and different systems are likely running different kinds of shells, a definitive list is impossible. Please see your shell’s documentation for a list of defined environment variables.

Other environment variables include the CGI variables, placed there regardless of whether PHP is running as a server module or CGI processor.

Examples

Example #1 $_ENV example

Assuming «bjori» executes this script

The above example will output something similar to:

Notes

Note:

This is a ‘superglobal’, or automatic global, variable. This simply means that it is available in all scopes throughout a script. There is no need to do global $variable; to access it within functions or methods.

See Also

User Contributed Notes 2 notes

If your $_ENV array is mysteriously empty, but you still see the variables when calling getenv() or in your phpinfo(), check your http://us.php.net/manual/en/ini.core.php#ini.variables-order ini setting to ensure it includes «E» in the string.

Please note that writing to $_ENV does not actually set an environment variable, i.e. the variable will not propagate to any child processes you launch (except forked script processes, in which case it’s just a variable in the script’s memory). To set real environment variables, you must use putenv().

Basically, setting a variable in $_ENV does not have any meaning besides setting or overriding a script-wide global variable. Thus, one should never modify $_ENV except for testing purposes (and then be careful to use putenv() too, if appropriate).

PHP will not trigger any kind of error or notice when writing to $_ENV.

Источник

bpolaszek / check-environment-variables.php

This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters

#!/usr/bin/env php
/**
* Checks that all environment variables are set before deploying.
*
* @author Beno!t POLASZEK — 2018
* @link https://gist.github.com/bpolaszek/559dbc341dec51303fc0dea8162cf735#gistcomment-2747882
*/
define( ‘PROJECT_DIR’ , dirname(__DIR__));
require_once PROJECT_DIR . ‘/vendor/autoload.php’ ;
use Symfony \ Component \ Console \ Application ;
use Symfony \ Component \ Console \ Input \ InputArgument ;
use Symfony \ Component \ Console \ Input \ InputInterface ;
use Symfony \ Component \ Console \ Input \ InputOption ;
use Symfony \ Component \ Console \ Output \ OutputInterface ;
use Symfony \ Component \ Console \ Style \ SymfonyStyle ;
use Symfony \ Component \ Dotenv \ Dotenv ;
use Symfony \ Component \ Dotenv \ Exception \ PathException ;
if (!class_exists( Dotenv ::class))
print( ‘Error: You probably forgot to `composer req [—dev] symfony/dotenv.` 😉’ ) . PHP_EOL ;
exit( 1 );
>
chdir( PROJECT_DIR );
( new Application ( ‘check:environment:variables’ ))
-> register ( ‘check:environment:variables’ )
-> addArgument ( ‘env-file’ , InputArgument :: IS_ARRAY , ‘(Optionnal) The .env file(s) to load.’ )
-> addOption ( ‘ignore-vars’ , null , InputOption :: VALUE_OPTIONAL , ‘Variables to ignore, separated by commas.’ )
-> addOption ( ‘no-error’ , null , InputOption :: VALUE_NONE , ‘Do not produce error messages.’ )
-> setCode ( function ( InputInterface $ input , OutputInterface $ output )
$ io = new SymfonyStyle ( $ input , $ output );
$ dotEnv = new Dotenv ();
$ distFile = getcwd() . ‘/.env.dist’ ;
if (!is_readable( $ distFile ) || is_dir( $ distFile ))
throw new PathException ( $ distFile );
>
$ definedVars = array_keys( $ dotEnv -> parse (file_get_contents( $ distFile , ‘.env.dist’ )));
$ ignoredVars = null === $ input -> getOption ( ‘ignore-vars’ ) ? [] : explode( ‘,’ , $ input -> getOption ( ‘ignore-vars’ ));
// Load environment variables
foreach ( $ input -> getArgument ( ‘env-file’ ) as $ envFile )
$ dotEnv -> load ( $ envFile );
>
// Compare
$ values = [];
foreach ( $ definedVars as $ variable )
$ values [ $ variable ] = getenv( $ variable );
>
$ missingVars = array_keys(
array_filter(
$ values ,
function ( $ value )
return false === $ value ;
>
)
);
// Display
if ( $ io -> isVerbose ())
$ rows = [];
foreach ( $ values as $ variable => $ value )
if (in_array( $ variable , $ ignoredVars ))
$ rows [] = [ $ variable , in_array( $ variable , $ missingVars ) ? ( ‘NOT SET (IGNORED)‘ ) : $ value ];
> else
$ rows [] = [ $ variable , in_array( $ variable , $ missingVars ) ? ( ‘MISSING‘ ) : $ value ];
>
>
$ io -> table ([ ‘Environment variable’ , ‘Value’ ], $ rows );
>
$ missingVars = array_diff( $ missingVars , $ ignoredVars );
if (count( $ missingVars ) > 0 )
if ( true !== $ input -> getOption ( ‘no-error’ ))
$ io -> error (sprintf( ‘Missing Environment variables: %s’ , implode( ‘, ‘ , $ missingVars )));
return 1 ;
>
$ io -> warning (sprintf( ‘Missing Environment variables: %s’ , implode( ‘, ‘ , $ missingVars )));
return 0 ;
>
$ io -> success ( ‘All environment variables are set. 👍’ );
return 0 ;
>)
-> getApplication ()
-> setDefaultCommand ( ‘check:environment:variables’ , true )
-> run ();

Introduction

This script will check if all environment variables defined in .env.dist are properly set.

Installation

  • Put it in the bin/ directory of your Symfony 4 project.
  • Insert it in your CI, once vendors are installed ( symfony/dotenv is required). It will cause your build to fail if there’s a missing environment variable.

Usage

./bin/check-environment-variables

✔️ Will check if your environment variables are properly set according to your .env.dist .

./bin/check-environment-variables .env

✔️ Will check if your environment variables + vars defined in .env file are properly set according to your .env.dist .

./bin/check-environment-variables --no-error

✔️ Will not return 1 in case of failure.

./bin/check-environment-variables -v

✔️ Will output an array of the variables defined in .env.dist and their values.

------------------------------- ----------------------------------- Environment variable Value ------------------------------- ----------------------------------- APP_ENV dev APP_SECRET 23a92e2185563187434706c01d2c7a8f PROXY_BASE_URI MISSING ------------------------------- -----------------------------------

Источник

How do I check whether an environment variable is set in PHP?

getenv() returns false if the environment variable is not set. The following code will work:

// Assuming MYVAR isn't defined yet. getenv("MYVAR") !== false; // returns false putenv("MYVAR=foobar"); getenv("MYVAR") !== false; // returns true 

Be sure to use the strict comparison operator ( !== ) because getenv() normally returns a string that could be cast as a boolean.

Solution 2

if($ip = getenv('REMOTE_ADDR')) echo $ip; 

getenv() Returns the value of the environment variable.

wecsam

I’m in college, and I have a part-time job.

Comments

// Assuming MYVAR isn't defined yet. isset(MYVAR); // returns false putenv("MYVAR=foobar"); isset(MYVAR); // returns true 

Isn’t REMOTE_ADDR always set? In my case, I’m writing a script that needs to act differently based on whether the server has an environment variable set.

Rajeev Ranjan

I figured out by myself that getenv() returns false if the environment variable is not set. I see that that is what your code tries to illustrate. However, there are several problems with your code. First of all, we try to avoid using the = assignment operator in if conditionals because we almost always meant == . Second of all, the value of the environment variable could be an empty string that casts to false , so we need to use a strict comparison operator.

Rajeev Ranjan

@wecsam I think its not comparison ,assign getenv(‘REMOTE_ADDR’) value to $ip and then checking for $ip .

I know that it’s not a comparison. What I’m saying is that we usually don’t do assignments in if conditionals.

Источник

Читайте также:  Swapping values in python
Оцените статью