18

I've been able to find information on how to use config vars in Heroku for Python, node.js, and some other languages, but not for PHP. Can you use them with PHP, or is it not supported?

This article shows how to do it for Python, Java, and Ruby, but not PHP.

mp94
  • 1,209
  • 3
  • 11
  • 23
  • The PHP config var doc (along with a lot of other important info on using PHP on Heroku) is in the Getting Started on Heroku with PHP tutorial provided by Heroku: https://devcenter.heroku.com/articles/getting-started-with-php#define-config-vars – Patrick Jun 12 '17 at 19:45

2 Answers2

39

Config vars on heroku manifest themselves as environment variables, so you should be able to access them from php like you would any other environment variable, eg. using getenv.

First, set the variable from your console:

heroku config:set MY_VAR=somevalue

Then, access it from your code:

$my_env_var = getenv('MY_VAR');
Moritz
  • 4,565
  • 2
  • 23
  • 21
  • You can see all vars on cmd with `heroku config` and get a specific with `heroku config:get ` – Timo Mar 09 '22 at 07:00
  • The Heroku vars are not available locally. but only on Heroku because they are Heroku config vars. With `heroku config` you do like an api call to the remote server. – Timo Mar 09 '22 at 07:06
1

Another solution without getenv()

While the top rated answer answers the question, I want to add a solution that works both remote and local with the Php Dotenv Package:

1.Grab the variables you need with heroku config -a <app>, here the mysql string:

CLEARDB_DATABASE_URL: mysql://<user>:<password>@<host>/<db>?reconnect=true

2.Prepare your app locally

composer.json

{
"require": {
    "vlucas/phpdotenv": "^5.4"
    }
}


.env
host_heroku= ''

the index

index.php
include "config.php";
// Db connection is built

the config

config.php
include realpath(__DIR__ . '/vendor/autoload.php');
$dotenv = Dotenv\Dotenv::createImmutable(__DIR__ . '/../');
$dotenv->load();
$db_hostname = $_ENV['host_heroku'];

3.Commit and push to heroku

Timo
  • 2,922
  • 3
  • 29
  • 28