Php Superglobals Env
Php Superglobals Env
The $_ENV superglobal in PHP is used to retrieve environment variables. These environment variables can be set in the server configuration, such as in the Apache or Nginx configuration files, or directly in the PHP script. They can be useful for storing configuration settings, credentials, and other data that should not be hardcoded in your scripts.
Accessing Environment Variables
Environment variables can be accessed using the $_ENV superglobal array. Here is an example of how to access an environment variable:
<?php $env_var = $_ENV['ENV_VAR']; echo "The value of ENV_VAR is: " . $env_var; ?>
Setting Environment Variables in Apache
To set an environment variable in Apache, you can use the SetEnv directive in the .htaccess file or the main Apache configuration file.
Setting Environment Variables in Apache
In an Apache configuration file (httpd.conf) or an .htaccess file, you can set environment variables using the SetEnv directive:
SetEnv ENV_VAR "myvalue"
Apache configuration (httpd.conf or apache2.conf)
<VirtualHost *:80> ServerName www.xyz.com SetEnv ENV_VAR "myvalue" </VirtualHost>
Setting Environment Variables in Nginx
http {
server {
listen 80;
server_name example.com;
location / {
env MY_ENV_VAR="my_value";
}
}
}
Setting Environment Variables in PHP
putenv() function
<?php
putenv("MY_ENV_VAR=myvalue");
$env_var = getenv("ENV_VAR");
echo "The value of ENV_VAR is: " . $env_var;
?>
PHP script
<?php require 'vendor/autoload.php'; $dotenv = Dotenv\Dotenv::createImmutable(__DIR__); $dotenv->load(); echo "User: " . $_ENV["USER"]; ?>
Important Notes php superglobals env