0

Environment Variables are used to set up the PHP application and the application runs smoothly. The issue that I'm facing is when I'm trying to reference the application's database connection file and run it from CLI.

Apache Set Up:

<VirtualHost *:80>
 DocumentRoot /var/www/html
 ServerName server.hostname.com
 SetEnv HOSTNAME 'hostname'
 SetEnv USERNAME 'username'
 SetEnv DB_PASSWORD 'password'
 SetEnv DB_NAME 'databaseName'
</VirtualHost>

The environment variables store all the connection-related data and the connection is referencing that.

Connection:

<?php

$username = $_SERVER['USERNAME'];
$password = $_SERVER['DB_PASSWORD'];
$hostname = $_SERVER['HOSTNAME'];
$database = $_SERVER['DB_NAME'];
error_reporting(0);
$mysqli = new mysqli($hostname, $username, $password, $database);

But, when I run it from CLI, it doesn't pick up the environment variables and it also doesn't let me run the cronjobs that are set up on the server because of the same reason.

1 Answer 1

2

When you run a PHP script via CLI, it has nothing to do with apache, so you won't have access to your variables.

There are other options:

  1. Set them in a PHP script and use include('/path/to/variables.php'); in your script.
  2. Set them globally on the system (can be dangerous)
  3. Pass them as command line options: php myscript.php var1 var2 and then you access them with $argv[1], $argv[2]
  4. Set the variable on the command line before calling the script: APPLICATION_ENV=staging php myscript.php The variable will be available in the $_SERVER array: $_SERVER['APPLICATION_ENV']. This will persist in the environment after your script has finished executing, which you may not want.

It really depends on your needs. Personally i think the first option is the simplest.

Read more about that here: Setting PHP enviromental variable while running command line script

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.