2

I'm trying to use a PHP function in .env file which is rand() in my case.

Here is what I'm trying to achieve in .env;

PROTOCOL="http"
DOMAIN="example.com"
URI="www.{$DOMAIN}"
RAND=rand(1,5)
CDN_URI="cdn{$RAND}.{$DOMAIN}"
CDN_URL="{$PROTOCOL}://{$CDN_URI}"

As you can see, I am trying to generate random integers from 1 to 5 which represent the CDN subdomain so that in a request I would get http://cdn2.example.com and in another one http://cdn4.example.com and so on.

I guess using PHP in .env is not natively supported but is there any way / workaround ?

P.S. I am using Laravel 5.

miken32
  • 42,008
  • 16
  • 111
  • 154
Sarpdoruk Tahmaz
  • 1,418
  • 3
  • 17
  • 25

2 Answers2

2

The .env file, as plain text, doesn't have support to PHP functions. This file was designed as a fallback for your environment variables (from the OS), so you cannot use PHP code on that. You can use a global variable to do something similar if you really need a global random number, instead:

global $rand;
$rand = rand(1,5);

Then where you need to use your number outside the main context (like inside functions), you'll need to declare global $rand:

function someFunction ()
{
    global $rand;
    doSomethingWithRand($rand);
}

But it's an ugly approach in my opinion. Depending on what you're trying to achieve, there is a better way to do that.

Update

Since you're using Laravel. You can add the call to rand() function in some of your config files, under /config/ dir, like: 'rand' => rand(1,5),. Then to access your random number, you should use:

// If your config was set inside /config/app.php.
config('app.rand');

// OR

// If your config was set inside /config/services.php, for instance.
config('services.rand');

Reference: http://laravel.com/docs/5.1/installation#accessing-configuration-values

Gustavo Straube
  • 3,744
  • 6
  • 39
  • 62
1

You can use PHP in your environment file by using a well syntax like that :

<?php
return array(
    'PROTOCOL' => "http",
    'DOMAIN' => "example.com",
    'URI' => "www.{$DOMAIN}",
    'RAND' => rand(1,5),
    'CDN_URI' => "cdn{$RAND}.{$DOMAIN}",
    'CDN_URL' => "{$PROTOCOL}://{$CDN_URI}",
);
Samuel Dauzon
  • 10,744
  • 13
  • 61
  • 94