hd.
hd.

Reputation: 18296

how to Access to environment variable using php

I have set a custom environment variable in debian using below command :

$ export my_var=1

I want to read this variable value using php. I have tried :

echo getenv('my_var');

if I call the php code from the command line using php command it is ok but when I access to php code using apache it doesn't echo anything.

Why is it so?

Upvotes: 0

Views: 1102

Answers (2)

João Paulo Cercal
João Paulo Cercal

Reputation: 763

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

Put your environment variables into "/etc/environment" and "/etc/apache2/envvars", after restart your Apache Server and load your environment variables to operational system:

# source /etc/environment
# source /etc/apache2/envvars

If you are running the application using a CLI basically export the variables:

export YOUR_ENV_VARIABLE_NAME="yourValue"

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";
// ...
var_dump(Cekurte\Environment\Environment::get("YOUR_ENV_VARIABLE_NAME"));

Enjoy it.

Upvotes: 0

V G
V G

Reputation: 19002

This is so, because your console has its own context with its own environment variables and Apache its own. Consider this answer to set the environment variables in apache.

Upvotes: 1

Related Questions