Skip to content

Instantly share code, notes, and snippets.

@Toflar
Last active November 7, 2018 12:09
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Toflar/37fcace7f54a20327e3cf51eaee83e15 to your computer and use it in GitHub Desktop.
Save Toflar/37fcace7f54a20327e3cf51eaee83e15 to your computer and use it in GitHub Desktop.
Symfony 4 index.php with env data for production
<?php
use App\Kernel;
use Symfony\Component\Debug\Debug;
use Symfony\Component\Dotenv\Dotenv;
use Symfony\Component\HttpFoundation\Request;
require __DIR__.'/../vendor/autoload.php';
// The check is to ensure we don't use .env in production
if (!isset($_SERVER['APP_ENV'])) {
if (!class_exists(Dotenv::class)) {
throw new \RuntimeException('APP_ENV environment variable is not defined. You need to define environment variables for configuration or add "symfony/dotenv" as a Composer dependency to load variables from a .env file.');
}
- (new Dotenv())->load(__DIR__.'/../.env');
+
+ $dotEnv = new Dotenv();
+
+ // Directly populate the .env data here but improve it at least a little bit
+ // by not parsing the .env file on every request
+ // Beware, this makes the .env file behave more like a parameters.yml so you
+ // can keep the same structure as you would have in bigger projects with real
+ // environment variables in production but in fact if you wanted to adjust
+ // the .env variables, you need to do both, change the .env file and delete
+ // the .env.php which will then be rewritten on first use.
+ if (!file_exists(__DIR__.'/../.env.php')) {
+ $variables = $dotEnv->parse(file_get_contents(__DIR__.'/../.env'));
+
+ file_put_contents(__DIR__.'/../.env.php', sprintf('<?php return %s;',
+ var_export($variables, true)
+ ));
+
+ } else {
+ $variables = require_once __DIR__.'/../.env.php';
+ }
+
+ $dotEnv->populate($variables);
}
$env = $_SERVER['APP_ENV'] ?? 'dev';
$debug = $_SERVER['APP_DEBUG'] ?? ('prod' !== $env);
if ($debug) {
umask(0000);
Debug::enable();
}
if ($trustedProxies = $_SERVER['TRUSTED_PROXIES'] ?? false) {
Request::setTrustedProxies(explode(',', $trustedProxies), Request::HEADER_X_FORWARDED_ALL ^ Request::HEADER_X_FORWARDED_HOST);
}
if ($trustedHosts = $_SERVER['TRUSTED_HOSTS'] ?? false) {
Request::setTrustedHosts(explode(',', $trustedHosts));
}
$kernel = new Kernel($env, $debug);
$request = Request::createFromGlobals();
$response = $kernel->handle($request);
$response->send();
$kernel->terminate($request, $response);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment